+ 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

2nd Dec 2020, 9:03 AM
Rik Wittkopp
Rik Wittkopp - avatar
6 Réponses
+ 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.
2nd Dec 2020, 10:29 AM
Nova
Nova - avatar
+ 3
Nova, Slick Thanks for that, I will try it out. PS: Looks like I will be learning about call stack now
2nd Dec 2020, 10:59 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 3
Nova Perfect, works now
2nd Dec 2020, 11:02 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 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
2nd Dec 2020, 10:33 AM
Slick
Slick - avatar
+ 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?
2nd Dec 2020, 9:45 AM
Slick
Slick - avatar
+ 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
2nd Dec 2020, 10:23 AM
Rik Wittkopp
Rik Wittkopp - avatar