project-euler/151_paper_sheets.py

25 lines
577 B
Python
Raw Normal View History

2023-03-25 17:24:17 +01:00
#!/usr/bin/env python3
from fractions import Fraction
def cut(state, i):
return state[:i] + (state[i]-1,) + \
tuple(n + 1 for n in state[i+1:])
def search(state=(1, 0, 0, 0, 0), cache={}):
if state in cache:
return cache[state]
if sum(state) == state[-1] == 1:
return 1
r = 0
for i, p in enumerate(state):
if not p:
continue
r += Fraction(p, sum(state)) * \
search(cut(state, i), cache)
r += (sum(state) == 1)
cache[state] = r
return r
print(float(round(search(), 6) - 2))