-
Notifications
You must be signed in to change notification settings - Fork 0
/
play24.py
78 lines (66 loc) · 2.19 KB
/
play24.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
#!/usr/bin/python -tt
import sys
import re
import itertools # http://docs.python.org/library/itertools.html#itertools.combinations
# GENERATOR FOR TEST PATTERNS
def testPatterns(args):
patterns = ['%f+%f+%f+%f',
'%f-%f-%f-%f',
'%f*%f*%f*%f',
'%f/%f/%f/%f',
'(%f+%f)*(%f+%f)',
'(%f-%f)*(%f-%f)',
'(%f+%f)*%f*%f',
'(%f-%f)*%f*%f',
'(%f-%f)*%f+%f',
'(%f-%f)*%f-%f',
'%f*(%f+%f)+%f',
'%f*(%f-%f)-%f',
'%f*(%f-%f)+%f',
'%f*(%f+%f)-%f',
'%f+(%f/%f)*%f',
'(%f/%f+%f)*%f']
for pattern in patterns:
yield pattern % (float(args[0]), float(args[1]), float(args[2]), float(args[3]))
# GENERATE ALL POSSIBLE COMBINATIONS FROM ARGS PROVIDED
# Code based on the following documetion
# http://docs.python.org/library/itertools.html#itertools.combinations
def combinations(iterable, r):
pool = tuple(iterable)
n = len(pool)
for indices in itertools.permutations(range(n), r):
yield tuple(pool[i] for i in indices)
# GAMEPLAY
def play24(ints):
target = 24
for int in ints:
print int
print "thinking..."
for combo in combinations(ints, 4):
#print "COMBO:", combo
for test in testPatterns(combo):
#print test, eval(test)
if eval(test) == target:
print "FOUND: ", test
return
print "no patterns result in %f" % target
def main():
ints = sys.argv[1:]
# IF NO ARGS PASSED, DEFINE A DEFAULT SET
if not ints:
print "usage: [--int 1-10][--int 1-10][--int 1-10][--int 1-10]";
ints = [4,10,4,2]
# MAKE SURE THERE ARE NO 0'S SO WE DON'T GET A DENOMINATOR ERROR
for i in ints:
if(i == 0):
print "no 0's please"
sys.exit(1)
# MAKE SURE WE'VE GOT 4 AND ONLY 4 ARGUMENTS
if len(ints) != 4:
print "only 4 arguments, please";
sys.exit(1)
play24(ints)
print "end"
# This is the standard boilerplate that calls the main() function.
if __name__ == '__main__':
main()