Skip to content

Instantly share code, notes, and snippets.

@bycoffe
Created March 6, 2010 01:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bycoffe/323418 to your computer and use it in GitHub Desktop.
Save bycoffe/323418 to your computer and use it in GitHub Desktop.
# 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