Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Collatz Conjecture]: Update recursion approach snippet #3484

Conversation

AndrewLawendy
Copy link
Contributor

@AndrewLawendy AndrewLawendy commented Aug 1, 2023

The current approach to recursion is not ideal, as it utilizes a suboptimal way of returning values.
This approach should not be encouraged or taught to students, as it may lead to the use of tail recursion.

An alternative approach to recursion, which is considered more ideal, can be found at https://exercism.org/tracks/python/exercises/collatz-conjecture/solutions/bobahop.

Reference: https://stackoverflow.com/questions/33923/what-is-tail-recursion

@AndrewLawendy AndrewLawendy changed the title fix(recusrion): 🐛 fix tail recursion bad approach [Collatz Conjecture]: Update recursion approach snippet Aug 1, 2023
@BethanyG
Copy link
Member

BethanyG commented Aug 1, 2023

@AndrewLawendy -- thanks for brining this up. However, I think you are misunderstanding Python and CPython here.

Python lacks any sort of tail call optimization (which you can also see is noted in the accepted answer of the iSO post you linked to). While the solution you link to has fewer steps due to the use of bit shifting, it is still tail-recursive, because Python is tail-recursive.

For more information, see this rundown by Al Sweigert, as well as this blog post by Guido van Rossum, the creator of Python.

You can also run each solution through python tutor to see the difference in steps, but the similarity in tail-calls.

@AndrewLawendy
Copy link
Contributor Author

Ah, OK, thanks for sharing that.

I come from a JS background, and this code could lead to stack overflow.
I'll check the references.

@BethanyG
Copy link
Member

BethanyG commented Aug 1, 2023

I come from a JS background, and this code could lead to stack overflow.

Yup. It will in Python as well, without memoization or careful management. If you read to the bottom of the approach, it talks a bit about Python's recursion limit due to this danger.

@BethanyG
Copy link
Member

BethanyG commented Aug 1, 2023

I am going to go ahead and close this. I've alerted the other author of the approach, who is going to review things and maybe add a little more explanation or links about how recursion works in Python. 🙂

@BethanyG BethanyG closed this Aug 1, 2023
@AndrewLawendy AndrewLawendy deleted the COLLATZ-CONJECTURE-RECURSION-APPROACH branch August 1, 2023 22:28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants