Permalink
Browse files

generator function version for python

  • Loading branch information...
1 parent 1680cab commit 25fa3c29dc8bdab62003037a8bf527d735067d56 @ivangonekrazy committed Feb 9, 2011
Showing with 21 additions and 0 deletions.
  1. +21 −0 collatzGenerator.py
View
@@ -0,0 +1,21 @@
+#
+# Collatz sequence generator.
+# (http://en.wikipedia.org/wiki/Collatz_conjecture)
+#
+# Python generator function version.
+#
+# Copyright (c)2011, Ivan Tam. ivan@hipnik.net
+#
+
+def collatzGen(n):
+ if n == 1: yield 1 # base case
+
+ while n > 1:
+ if n % 2 == 1: n = n * 3 + 1
+ if n % 2 == 0: n = n / 2
+ yield n
+
+if __name__ == '__main__':
+ print [ x for x in collatzGen(1024)]
+ print [ x for x in collatzGen(50)]
+ print [ x for x in collatzGen(1)]

0 comments on commit 25fa3c2

Please sign in to comment.