Recursion in Python 3

0

I'm having trouble organizing a recursive sum formula in Python. I 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, thank you in advance!

    
asked by anonymous 02.01.2018 / 22:38

2 answers

1

Should the formula 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
    
03.01.2018 / 07:45
0

I was able to analyze the error. The recursion would go to infinity because it did not call the formula again. For 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)
    
04.01.2018 / 00:41