Permalink
Browse files

renamed start variable

  • Loading branch information...
1 parent 891cf9a commit 22ec2d09e59e38d57323e02c558a53aed4dc9c8a @ivangonekrazy committed Feb 9, 2011
Showing with 29 additions and 0 deletions.
  1. +29 −0 collatz.py
View
@@ -0,0 +1,29 @@
+#
+# Collatz sequence generator.
+# (http://en.wikipedia.org/wiki/Collatz_conjecture)
+#
+# Recursive (with accumulator) Python version.
+#
+# Copyright (c)2011, Ivan Tam. ivan@hipnik.net
+#
+
+def collatz(n, acc=None):
+ # if the accumulator is not set, give it a head
+ if acc is None: acc = [n]
+
+ # base case
+ if n == 1: return [1]
+
+ if n % 2 == 1: # odd case
+ next = n * 3 + 1
+ elif n % 2 == 0: # even case
+ next = n / 2
+
+ acc.append( next )
+ collatz( next, acc )
+ return acc
+
+if __name__ == '__main__':
+ print collatz(1024)
+ print collatz(50)
+ print collatz(1)

0 comments on commit 22ec2d0

Please sign in to comment.