Created
March 6, 2010 01:37
-
-
Save bycoffe/323418 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
# http://xkcd.com/710/ | |
# An iterator for showing the Collatz Conjecture | |
""" | |
>>> [x for x in Collatz(6)] | |
[3, 10, 5, 16, 8, 4, 2, 1] | |
>>> [x for x in Collatz(11)] | |
[34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1] | |
>>> len([x for x in Collatz(27)]) | |
111 | |
""" | |
class Collatz(object): | |
def __init__(self, start): | |
self.start = int(start) | |
self.n = self.start | |
def __iter__(self): | |
return self | |
def next(self): | |
if self.n == 1: | |
raise StopIteration | |
elif self.n % 2 == 0: | |
self.n = self.n / 2 | |
else: | |
self.n = (self.n*3) + 1 | |
return self.n | |
if __name__ == '__main__': | |
import doctest | |
doctest.testmod() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment