Solve problem 112 and add custom cache decorator
This commit is contained in:
37
python/e112.py
Normal file
37
python/e112.py
Normal 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)
|
||||||
|
|
||||||
@@ -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
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user