Search code examples
pythonloopsfloating-pointsumrounding

How to use a loop then calculate the sum of a list?


I need to write a function "sum_reciprocals()" which takes 1 input argument, a positive integer "n", and returns 1 output value, the sum of the reciprocals of all integers from 1 to n (inclusive). The result should be returned as a floating point number, and rounded to 5 decimal places.

here is my code

def sum_reciprocals(n):
    x = [1]
    n = 10000
    for i in range(2,n+1):
        x.append(x[i-2]+1/x[i-1])
    sum_reciprocals = round(sum(x))
    return sum_reciprocals

But it says that "IndexError: list index out of range" on my fifth line.


Solution

  • Can't really understand what's the point of this

    x.append(x[i - 2] + 1 / x[i - 1])
    

    You can just iterate from 1 to n with i and add 1 / i to the total sum, like so

    def sum_reciprocals(n):
        total = 0
        for i in range(1, n + 1):
            total += 1 / i
    
        return total
    

    or using list comprehension with sum() function

    def sum_reciprocals(n):
        return sum([1 / i for i in range(1, n + 1)])
    

    or even adding lambda expression to this

     sum_reciprocals = lambda n: sum([1 / i for i in range(1, n + 1)])
    

    Although last one will be a violation of PEP 8 E731 Code style standart (but it's good to know you can do that)