0

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.

  • In your own words, where the code says `x.append(x[i-2]+1/x[i-1])`: what do you expect will be the value of `i`, the first time through the loop? Therefore, what indices will be used in order to look into `x`? What does `x` contain before the loop starts? How many values is that? Therefore, what indices are valid? What is the intended purpose of this logic? – Karl Knechtel Nov 12 '22 at 00:45

2 Answers2

1

Your list only has one element, but in the first iteration of the for loop you try to access the 0-th and the 1st element :)

TECHNOFAB
  • 121
  • 10
1

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)

sudden_appearance
  • 1,968
  • 1
  • 4
  • 15