Sum of the first nth term of Series

Viewed 1377
def series_sum(n):
    listSeries = [1, 1/4, 1/7, 1/10, 1/13, 1/16, 1/19, 1/22, 1/25]
    sum = 0.00
    for i in range(n):
        sum += listSeries[i]
    return str("{:.2f}".format(sum))

Hey guys, my code passes all tests and kind of works with this challenge, but I get one annoying error, which I don't know how to solve. List index out of range. list[i-1] didn't work out. I hope it is not necessary to rewrite the whole code to fix this. codewars.com/kata/555eded1ad94b00403000071/train/python

Traceback (most recent call last):
  File "main.py", line 13, in <module>
    Test.assert_equals(series_sum(15), "1.94")
  File "/home/codewarrior/solution.py", line 5, in series_sum
    sum += listSeries[i]
IndexError: list index out of range

Thanks.

4 Answers

What about:

def series_sum(n):
    return '{:.2f}'.format(sum(1/(1+i*3) for i in range(n)))

print(series_sum(15))

Result:

1.94

I took a look at the link you sent, and I suggest that you generate the list depending on the value of n so that you don't get an IndexError:

def series_sum(n):
    fractions = []
    for n in range(1, 3*n - 1, 3):
        fractions.append(1/n)
    return "{:.2f}".format(sum(fractions))

I tested the code on the website, and it worked for all the solutions.

The thing is that there are no elements in your list after element at index 8 (Position 9) So, when you try to use for i in range(n) with the value of n=15 It gives you an error.

One of the ways you could avoid this, is adding an if statement at the top of your code like this:

def series_sum(n):
    l1 = [1, 1/4, 1/7, 1/10, 1/13, 1/16, 1/19, 1/22, 1/25] #You cant use list as a variable name
    if len(l1) < n:
        n = len(l1) #Or do something else here that you wish to do
    #Note: doing n = l1 here will give you the sum of the entire list if n > length of list
    sum = 0.00
    for i in range(n):
        sum += l1[i]
    return str("{:.2f}".format(sum))

It is only about exceptions on your system. You must be sure for the

  len(listSeries) > n
Related