Recursion in Python 3
I'm having a hard time organizing a recursive summation formula in Python. Need to calculate:
My Code:
def seq1(n):
if n == 1:
return n
return seq1(n-1)+(-1**(n+1)/n)
I get the same error for almost every change:
RecursionError: maximum recursion depth exceeded in comparison
I would like to know how to do the calculation, grateful right now!
1
2 answers
Does the formula need to be necessarily recursive? that is, call the function itself? I think the most elegant way would be to use a ' for ' and calculate the series numerically.
def seq(n):
val=0
for i in range(n):
val += (-1**(n+1)/n)
return val
3
Author: Henrique Hafner, 2018-01-03 06:45:19
I managed to parse the error. Recursion would go to infinity because it wouldn't call the formula again. For the curious, the correct code below:
def seq1(n):
if n >= 1:
if n == 1:
return (-1**(n+1)/n)
return seq1(n-1)+(-1**(n+1)/n)
1
Author: Breno Nahuz, 2018-01-03 23:41:02