Skip to content

Nth term#2

Open
julienawilson wants to merge 8 commits intomasterfrom
nth-term
Open

Nth term#2
julienawilson wants to merge 8 commits intomasterfrom
nth-term

Conversation

@julienawilson
Copy link
Owner

Weekend Code-Wars Assignment.


def series_sum(n):
"""Find the sum of the first nth terms of a series 1+1/4+1/7+..."""
sum = 0

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bad variable name. Python has a built-in sum() function, and your editor should have highlighted it differently because of this fact. Typically when I'm trying to find the sum of something, I call the resultant value something like "total" or "result" just to avoid this.

"""Find the sum of the first nth terms of a series 1+1/4+1/7+..."""
sum = 0
for i in range(n):
sum += float(1 / (1 + i * 3))

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In Python 2, this is integer division even if you use the float type object to turn it into a float after the fact. Thus, all your answers will be "1"

sum = 0
for i in range(n):
sum += float(1 / (1 + i * 3))
return str("%.2f" % sum)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're already using string formatting to turn your resultant total into a string. Why are you calling the str() type object to turn it into a string again?

def test_series_sum(n, result):
"""Test series_sum() for proper output in test cases."""
from series_sum import series_sum
assert series_sum(n) == result

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Your tests fail in Python 2 and you're not accounting for when n=0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants