+ 2
Why is my function recursion doesn't work(python)?
Good day, I got none being returned by a function which calls itself. It's a simple function below that returns a sum of digits in a number. If it doesn't do a recursion it works fine though. I used a debugger and saw that the variable had a value but then I jumps to the else option and looses it. Why is it so? https://code.sololearn.com/cA7a5A1787a1/?ref=app
3 Respostas
+ 5
As Jazz said, you should use return on your recursive function call. That is because your recursive function returns back to where it has been called from(itself), which makes the function in total return NONE result.
This code works fine:
# this code has bugs
def digital_root(n):
sum=0
y=0
#============we cound the sum here
while y<len(str(n)):
sum+=int(str(n)[y])
y+=1
#===============
#we define if sum is 1 digit or not
if len(str(sum))==1:
return sum #we are stopping the function
else:
#or we are using the same function inside of it
return digital_root(sum)
print(digital_root(16)) #outputs 7
print(digital_root(942)) #outputs NONE
+ 2
Dunaev Evgenii Here are two alternatives:
#1
def foo(n):
n % 10 + foo(n // 10) if n else 0
#2
foo = lambda n: sum((int(x) for x in str(n)))
# Hope this helps