Created
November 5, 2016 09:45
-
-
Save popey456963/3ad4ac733775f20764339c55e1439641 to your computer and use it in GitHub Desktop.
Collatz Conjecture Memoisation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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