+ 4
def return query
The following code reduces the sum of the digits to 1 using recursion The return stops the recursion, but does not produce the result attached to the return. Can any-one help me understand why? https://code.sololearn.com/c92Kp0vLA5r3/?ref=app
6 ответов
+ 9
I think you just need to return happy(x) while calling it recursively.
Though it's calculating the happy number correctly but one thing we need to keep in mind is the call stack.
Once x reaches the value of 1, it returns 'Happy' and goes one down the call stack where nothing is being returned currently and hence you get None as the final returned value.
+ 3
Nova Perfect, works now
+ 2
Rik Wittkopp Nova's got it! About that call stack... so even after you return in a function the rest of the function runs? that's where i got stuck
+ 1
I single stepped through it and it's just a mess haha. Every iteration I ended up getting a name error because 'x isn't defined', then when it finally gets to 1, it just skips right over return and keeps calling itself. What kind of program are you trying to make?
+ 1
Slick 😂🤣😂
There is a concept I stumbled across recently called Happy Number
The concept being that the sum of the digits squared will eventually reduce to 1.
I am attempting to do this recursively when I noted this problem that the recursion reaches 1, which stops the recursion, yet doesn't return Happy
The print lines in the code are to show the recursion during development