-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolver.py
78 lines (66 loc) · 2.39 KB
/
solver.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import argparse
class Solver24:
def __init__(self, nums):
self.nums = nums
def build_permutations(self):
permutations = []
for a in self.nums:
for b in self.nums:
if b == a:
continue
for c in self.nums:
if c in [a, b]:
continue
for d in self.nums:
if d in [a, b, c]:
continue
permutations.append([a, b, c, d])
return permutations
def build_ops(self):
ops = ['+', '-', '*', '/']
ops_permutations = []
for a in ops:
for b in ops:
for c in ops:
ops_permutations.append([a, b, c])
return ops_permutations
def solve(self):
permutations = self.build_permutations()
ops_permutations = self.build_ops()
res = set()
for p in permutations:
for ops in ops_permutations:
a, b, c, d = p
op1, op2, op3 = ops
# (( a . b ) . c ) . d
# ( a . ( b . c ) ) . d
# a . (( b . c ) . d )
# a . ( b . ( c . d ))
# ( a . b ) . ( c . d )
# a . b . c . d
expressions = [
f'(({a} {op1} {b}) {op2} {c}) {op3} {d}',
f'({a} {op1} ({b} {op2} {c})) {op3} {d}',
f'{a} {op1} (({b} {op2} {c}) {op3} {d})',
f'{a} {op1} ({b} {op2} ({c} {op3} {d}))',
f'({a} {op1} {b}) {op2} ({c} {op3} {d})',
# f'{a} {op1} {b} {op2} {c} {op3} {d}' - This last case is covered by the first five
]
for expr in expressions:
try:
if eval(expr) == 24:
res.add(expr)
except ZeroDivisionError:
pass
print(res)
return res
def main():
parser = argparse.ArgumentParser(description="Let's play 24.")
parser.add_argument('nums', metavar='N', type=int, nargs=4,
choices=range(1, 14),
help='Choose 4 numbers from 1 to 13.')
args = parser.parse_args()
solver = Solver24(args.nums)
solver.solve()
if __name__ == '__main__':
main()