Sum of the first nth terms of series

This is my code

def series_sum(n):
    lst = []
    if n == 1:
        lst.append("1.00")
        return lst
    else:
        lst =["1.00"]
    first_deno = 4
    for numbers in range(2,n+1):
        print("the numbers",numbers)
        answer=float(lst[numbers-2]) + 1/first_deno
        print("the answer",answer)
        lst.append(round(answer,2))
        first_deno += 3
    return str((lst[-1]))
   
print(series_sum(5))

The Exercise

Your task is to write a function which returns the sum of following series upto nth term(parameter).

  • You need to round the answer to 2 decimal places and return it as String.
  • If the given value is 0 then it should return 0.00
  • You will only be given Natural Numbers as arguments.

Examples of output is
1 → 1 → “1.00”
2 → 1 + 1/4 → “1.25”
5 → 1 + 1/4 + 1/7 + 1/10 + 1/13 → “1.57”

Link:

It is giving me an error here, I don’t understand why

Traceback (most recent call last):
File “tests.py”, line 2, in
from solution import series_sum
File “/workspace/default/solution.py”, line 15
first_deno += 3
^
SyntaxError: invalid syntax

Me neither - I copied the code and it runs without problem.

That said, that’s a highly inefficient way to write this. You are creating a pointless list and not utilizing the range-object properly.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.