Created
December 6, 2017 15:38
-
-
Save arrieta/9d23f2ed648f1a71b709b63d4d4b0360 to your computer and use it in GitHub Desktop.
Minimum transformations from N to 1
This file contains 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 T(n): | |
memo = { | |
1 : (0, "<Base>"), | |
2 : (1, " / 2"), | |
3 : (1, " / 3") | |
} | |
def build_memo(n): | |
nonlocal memo | |
if n in memo: return memo[n] | |
value, _ = build_memo(n - 1) | |
op = " - 1" | |
if n % 2 == 0: | |
new_value, new_op = build_memo(n / 2) | |
if new_value < value: | |
value = new_value | |
op = " / 2" | |
if n % 3 == 0: | |
new_value, new_op = build_memo(n / 3) | |
if new_value < value: | |
value = new_value | |
op = " / 3" | |
memo[n] = (1 + value), op | |
return memo[n] | |
build_memo(n) | |
return memo | |
def U(N): | |
memo = { | |
1 : (0, "<Base>"), | |
2 : (1, " / 2"), | |
3 : (1, " / 3") | |
} | |
for n in range(4, N + 1): | |
value = memo[n - 1][0] | |
op = " - 1" | |
if n % 2 == 0: | |
new_value = memo[n/2][0] | |
if new_value < value: | |
value = new_value | |
op = " / 2" | |
if n % 3 == 0: | |
new_value = memo[n/3][0] | |
if new_value < value: | |
value = new_value | |
op = " / 3" | |
memo[n] = (1 + value), op | |
return memo | |
ops = { | |
" - 1": lambda x : int(x - 1), | |
" / 2": lambda x : int(x / 2), | |
" / 3": lambda x : int(x / 3), | |
} | |
def solve(n): | |
import math | |
from time import perf_counter | |
if n == 1: | |
print("You are at one already... " | |
"what's wrong with you?") | |
return | |
tbeg = perf_counter() | |
memo = U(n) | |
tend = perf_counter() | |
elapsed = (tend - tbeg) | |
print(f"{n} --> 1 in {memo[n][0]} steps") | |
max_width = math.floor(math.log(n, 10)) + 1 | |
while n != 1: | |
op = memo[n][1] | |
m = ops[op](n) | |
print(f"{n:>{max_width}d}{op} = {m:>{max_width}d}") | |
n = m | |
print(f"[{len(memo)} memo entries in {elapsed:.4f} seconds]") | |
def main(): | |
try: | |
while True: | |
n = input(">>> enter a new number: ") | |
solve(int(n)) | |
except (ValueError, KeyboardInterrupt): | |
pass | |
finally: | |
print("goodbye!") | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample console session