What's the difference between using return and print in this recursive function that calculates the sum of numbers?

0

I did a simple function in Python to give me the sum of the numbers from n to 0:

def retorna(n, zero, soma):
    if n <= zero:
        soma += n
        return soma
        retorna(n+1, zero, soma)
ret = retorna(1, 5, 0)
print(ret)

The result of the function, as is, is 1. But if I put print (soma) instead of return soma (and call function without print ), it gives me:

1, 3, 6, 10, 15. 

Why does this happen? I wanted to be able to display only the last result, 15, in the case.

Can you help me and give me another example so I can understand?

    
asked by anonymous 08.09.2018 / 15:27

2 answers

3

First: This code works best iteratively rather than recursively. Leave it to learn recursion with problems that need to be recursive and learn better.

A basic error is that it is not returning the result of the recursion, it is just calling the function and throwing away its result. And it's still doing it conditionally since it's within if , it can not, it should run every time except the last one.

The code could have the most significant variable name to know what it is about. The sum of n looks like a nonsense line there, should have the sum in the recursive function.

Except for the last time the return must always be the result of the function itself, every recursion is like this.

def retorna(valor, limite, soma):
    if valor > limite:
        return soma
    return retorna(valor + 1, limite, soma + valor)
print(retorna(1, 5, 0))

See running on ideone . And no Coding Ground . Also I put GitHub for future reference .

    
08.09.2018 / 16:29
1

If the function should return the sum of a set of integers, we can mathematically define the problem. Consider that the range is defined by a and b : [a, b] , being b greater than or equal to a . So we have:

Thisexpressioncanbeexpandedas:

Andit'strivialtorealizethatitcanberewrittenas:

Thatisnothingmorethantherecursiveformofthesumfunction.Butthiscannotbeinfinite,otherwiseyourprogramwillrunforever.Weneedasituationwhererecursivewritingcanbesimplified,generatingwhatwecallastopcondition.

Forthisexample,wecananalyzethesituationwhentheinterval[a,b]arrivesintheparticularcasewhereaisequaltob,being:

That is, when a = b , we know that the sum will be only b .

So, we can define our function somar , which receives the values a and b :

def somar(a, b):
    return a + somar(a+1, b) if a < b else b

So, as expected, when we do somar(1, 5) we get the result 15.

    
10.09.2018 / 15:57