Saturday, March 06, 2010

Iterative Collatz in Python (with resume)

I'm assumming there will be a lot of people looking to play with Collatz soon.

Here's a non-recursing version that will resume when you restart it.
Given all numbers to 2^58 have already been checked you might be there a while...

It's trivial to get it to dump a CSV with the steps for graphing, but, this one doesn't do that (but gives you the steps so that you can).

If you don't know what this is for, it doesn't matter.. (but you can google it...)

import os
def collatz(n):
 steps = []
 stAppend = steps.append
 while n > 1:
  stAppend(n)
  
  while not (n & 0x1):
   n >>= 1
   stAppend(n)

  if n == 1:
   break
  n = n * 3 + 1
 return steps

if __name__ == '__main__':
 n = 2
 if os.access('collatz.prg', os.F_OK|os.R_OK|os.W_OK):
  n = int(open('collatz.prg', 'rb').read())

 while True:
  steps = collatz(n)
  open('collatz.prg', 'wb').write(str(n))
  print n, len(steps)
  n += 1

No comments: