Solve problem 112 and add custom cache decorator

This commit is contained in:
2021-04-25 10:20:21 -04:00
parent 1883768d08
commit 26b11ed519
2 changed files with 49 additions and 0 deletions

37
python/e112.py Normal file
View File

@@ -0,0 +1,37 @@
def is_increasing(n_str):
if len(n_str) < 2:
return True
if n_str[0] <= n_str[1]:
return is_increasing(n_str[1:])
return False
def is_decreasing(n_str):
if len(n_str) < 2:
return True
if n_str[0] >= n_str[1]:
return is_decreasing(n_str[1:])
return False
def is_bouncy(n_str):
return not (is_increasing(n_str) or is_decreasing(n_str))
def euler_112():
n, n_bouncy = 0, 0
while True:
n += 1
if is_bouncy(str(n)):
n_bouncy += 1
ratio = n_bouncy / n
if ratio >= 0.99:
return n
if __name__ == "__main__":
solution = euler_112()
print("e112.py: " + str(solution))
assert(solution == 1587000)

View File

@@ -218,3 +218,15 @@ def is_permutation(n, p):
for p_n in str(p): for p_n in str(p):
digit_counts_p[int(p_n)] += 1 digit_counts_p[int(p_n)] += 1
return digit_counts_n == digit_counts_p return digit_counts_n == digit_counts_p
def cache(f):
cache = {}
def func_cached(*args):
if args in cache:
return cache[args]
r = f(*args)
cache[args] = r
return r
return func_cached