Skip to content

Instantly share code, notes, and snippets.

@popey456963
Created November 5, 2016 09:45
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 popey456963/3ad4ac733775f20764339c55e1439641 to your computer and use it in GitHub Desktop.
Save popey456963/3ad4ac733775f20764339c55e1439641 to your computer and use it in GitHub Desktop.
Collatz Conjecture Memoisation
def memo(f):
def func(*args):
if args not in func.cache:
func.cache[args] = f(*args)
return func.cache[args]
func.cache = {}
return func
@memo
def collatz(n):
if n == 1:
count, seq = 0, []
elif n % 2:
count, seq = collatz(3 * n + 1)
else:
count, seq = collatz(n // 2)
return count + 1, [n] + seq
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment