Recursion in Python 3

Asked

Viewed 649 times

1

I’m having trouble organizing a recursive summation formula in Python. I need to calculate:

inserir a descrição da imagem aqui

My code:

def seq1(n):
    if n == 1:
        return n
    return seq1(n-1)+(-1**(n+1)/n)

I keep getting the same error for almost every change:

RecursionError: maximum recursion depth exceeded in comparison

I would like to know how to do the calculation, thanks in advance!

  • 1

    For any 0 < n < 997 its function seems to work (I did not check the results). If you need to calculate for values outside this range, recursiveness is not the solution, but for didactic purposes, read on sys.setrecursionlimit

  • Thank you Anderson!

2 answers

3


Does the formula need to be necessarily recursive? i.e., calling 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
  • I would, but I was able to identify the error, thank you!

  • I found two errors in your iterative alternative: (1) you are not using the i account, but the constant n; (2) range with only one parameter generates numbers in the range [0, n), which is not the intention of the formula, but numbers in the range [1, n] (even avoid a division by zero when using the iteration variable of the first item I pointed out)

1

I was able to analyze the error. The recursion would go to infinity because it would 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)
  • Ignoring the indentation error of your answer, I must disagree that it is the correction. How the domain of the function is N*, your solution would only make a guarantee that one is working in the appropriate domain. I agree with @Andersoncarloswoss' comment on the question

Browser other questions tagged

You are not signed in. Login or sign up in order to post.