Recursion Problem in Python

Asked

Viewed 127 times

0

It’s my first question here, so I’ll be brief: I’m having trouble with the code below:

def nat(n):
  if n == 50:
     return 0
  else:
     return nat(n+1)
print(nat(1))

Turns out it’s a recursive question in Python, I must print the first 50 natural numbers, but my output always returns '0':

0

I don’t understand almost anything about it, I have already solved the issue in C and Python, but using repetition structures, but in this way that was presented to me, I am not managing to solve the same problem. Does anyone have an orientation as to where the error(s) is? Reminder, I don’t need problem solving, just a guide to where I’m missing, if possible.

  • There are two returns on the function n: one returns a recursive call, without changing its result at all; the other returns 0, simply. Thus, you can return 0 or return the computation of something without applying any change, and that computation always returns 0. (I am ignoring entries greater than 50, which would be infinite and would never return)

  • It was not very clear to me, so I could give an example, friend? (As I mentioned above, I’m a bit of a layman, rs)

  • According to its function, I will take from 48 and check the resulting value, nat(48) ==> nat(48+1) ==> nat(48+1+1) ==> 0

  • Ahh, thanks a friend

1 answer

2


In your code you are doing the following:

#define a  função nat
def nat(n):
    if n == 50:
        return 0
    else:
        return nat(n+1)

#chama a função para printar o valor retornado
print(nat(1))

So far so good, the return is in accordance with what you described.

You call the function with value n=1, as the value of n is not equal to 50 will return the value of nat(n=2), and so on until after all n=50 and returns 0, which is the imprinted value.

So in your code: nat(1) = nat(2) = nat(3) = ... = nat(50) = 0

I believe it’s a small problem of endentation with a few minor adjustments.

I think it would be this ,or something close, what you want to do:

#Define a função
def nat(n):
    if n == 50:
        return
    else:
        #printa e faz a chamada recursiva
        print(n)
        nat(n+1)

#chama a função
nat(1)
  • Yes, it worked perfectly, it was exactly that, but it stops at 49, but for that was only helping the base case from 50 to 51... I was vacillating, I would never give the right value, I would always return '0', because I was assigning 0 to the return in the condition of the base case, haha. I was not knowing how to endear correctly. Thanks buddy, it was of great help =D

Browser other questions tagged

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