How to keep a fixed value within a recursive function?

Asked

Viewed 244 times

0

I would like to create a variable with the first value passed as parameter in a function, but every time a recursive call is made the variable receives the value of the new parameter passed. For example:

def fatorial(n)
    print(n)
    if n <= 1:
        return 1
    else:
        return n * fatorial(n - 1)

In the above case I would like to print only the value passed as parameter the first time. Is there any way I can store and print only the first value passed? If so, how could I implement this?

1 answer

2


It is not necessary to store the value passed for the first time. Instead, use a control variable to decide whether or not to print the first value.

def fatorial(n, imprima=False):
    if imprima:
      print(n)
    if n <= 1:
        return 1
    else:
        return n * fatorial(n - 1)

print(fatorial(5, True))

Online example here.

  • It worked, but there’s some other way to store in a variable?

  • @Rafaellima you could store the value of the parameter within the condition if imprima.

  • Since you only want the first printed value, I don’t see why this should be done within the function.

  • While trying to store and use the variable later is still giving error, but the impression of the value already solves my problem.

  • In fact, the most common - and what I like - is to leave the default value of the optional value set to whoever calls the function "from outside" - the recursive function "knows more about itself" - (that is, Voce is thinking about her code when she writes the calls to herself)And it’s best that those internal calls go over the extra optional parameters. In short, change the cabbage to def fatorial(n, imprima=True): and the internal call to fatorial(n - 1, imprima=False) so who calls from outside need not worry about the "print".

  • Having said all this - it is a bad idea that a function of these 0- which is purely numerical, prints something - the best practice is even the recursive function only return a value - whoever makes the outside call that prints.

  • If it is a real code (in contrast to this example that is only didactic) where what will be done with the final value returned is more complicated than a simple print - still worth keeping the recursive function without a "special case` for when it is called from outside -and instead create another small function, which only takes care of calling the recursive function, and print or save its results.

Show 2 more comments

Browser other questions tagged

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