Day07
This commit is contained in:
parent
1380ad1b0b
commit
f0fdbb6161
1 changed files with 41 additions and 0 deletions
41
day07.py
Normal file
41
day07.py
Normal file
|
@ -0,0 +1,41 @@
|
||||||
|
#!/usr/bin/env python3
|
||||||
|
from copy import copy
|
||||||
|
|
||||||
|
puzzle = []
|
||||||
|
with open("day07") as f:
|
||||||
|
for l in f:
|
||||||
|
(res, n) = l.split(':')
|
||||||
|
ns = list(map(int, n.strip().split(' ')))
|
||||||
|
puzzle.append((int(res), ns))
|
||||||
|
|
||||||
|
# 1
|
||||||
|
def calc(res, ns, cur):
|
||||||
|
if cur == res: return True
|
||||||
|
if cur > res: return False
|
||||||
|
if len(ns) == 0: return False
|
||||||
|
|
||||||
|
n = ns.pop(0)
|
||||||
|
return calc(res, copy(ns), cur+n) or calc(res, copy(ns), cur*n)
|
||||||
|
|
||||||
|
res = 0
|
||||||
|
for p in puzzle:
|
||||||
|
if calc(p[0], copy(p[1][1:]), p[1][0]):
|
||||||
|
res += p[0]
|
||||||
|
print(res)
|
||||||
|
|
||||||
|
# 2
|
||||||
|
def calc2(res, ns, cur):
|
||||||
|
if len(ns) == 0 and res == cur: return True
|
||||||
|
if cur > res: return False
|
||||||
|
if len(ns) == 0: return False
|
||||||
|
|
||||||
|
n = ns[0]
|
||||||
|
return (calc2(res, copy(ns[1:]), cur+n)
|
||||||
|
or calc2(res, copy(ns[1:]), cur*n)
|
||||||
|
or calc2(res, copy(ns[1:]), int(str(cur)+str(n))))
|
||||||
|
|
||||||
|
res = 0
|
||||||
|
for p in puzzle:
|
||||||
|
if calc2(p[0], copy(p[1][1:]), p[1][0]):
|
||||||
|
res += p[0]
|
||||||
|
print(res)
|
Loading…
Reference in a new issue