Last active
August 4, 2021 16:24
-
-
Save juandesant/f6524331474ce46e0160ebea51640c51 to your computer and use it in GitHub Desktop.
Python implementation of the Collatz series as a generator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def next_collatz(n): | |
if n%2 == 0: | |
return n//2 | |
else: | |
return 3*n+1 | |
def collatz(n): | |
yield n | |
result = next_collatz(n) | |
while result != 1 and result : | |
yield result | |
result = next_collatz(result) | |
# when we arrive here, the final result is 1 | |
yield 1 | |
return | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment