project-euler/178_step_numbers.py

43 lines
877 B
Python
Raw Normal View History

2023-03-25 17:24:17 +01:00
#!/usr/bin/env python3
conds = ["any", "both", "nine"]
cache = {c : {n : dict() for n in range(10)} for c in conds}
def f(n, i, contains = "both"):
if i in cache[contains][n]:
return cache[contains][n][i]
if i == 1:
if contains == "both":
r = 0
elif contains == "any":
r = 1
elif contains == "nine":
r = (n == 9)
cache[contains][n][i] = r
return r
g = lambda x,y: f(x, i-1, y)
flag = contains
if n == 0 or n == 9:
if contains == "both":
flag = "nine"
elif contains == "nine" and n == 9:
flag = "any"
r = g(1, flag)
else:
r = g(n-1, contains) + g(n+1, contains)
cache[contains][n][i] = r
return r
places = 40
s = 0
for p in range(1, places+1):
s += sum(f(n, p) for n in range(1,10))
print(s)