#! /usr/bin/env python
class DivideError: pass
class SuffixExprError: pass
def all_perms(L):
if len(L) <= 1:
yield L
else:
for p in all_perms(L[1:]):
for i in range(len(p) + 1):
yield p[:i] + L[0:1] + p[i:]
def eval_two(a, b, o):
funcs = {'+': lambda x, y: x + y,
'-': lambda x, y: x - y,
'*': lambda x, y: x * y,
'/': lambda x, y: x // y,
}
if o == '/':
if a % b:
raise DivideError
x = funcs[o](a, b)
return x
def eval_suffix(La, Lo):
ia = io = 0
la = len(La)
lo = len(Lo)
Ta = []
x = 0
if la - lo != 1:
raise SuffixExprError
for ia in range(la):
if len(Ta) == 1:
o = Lo[io]
io += 1
x = eval_two(Ta[0], La[ia], o)
Ta[0] = x
else:
Ta.append(La[ia])
return Ta[0]
def eval_24pt(L, doall):
operands = []
operators = []
ops = '+-*/'
for o1 in ops:
for o2 in ops:
for o3 in ops:
operators.append([o1,o2,o3])
for x in all_perms(L):
operands.append(x)
for a in operands:
for o in operators:
try:
if eval_suffix(a, o) == 24:
print a, o
if doall == 0:
return
except DivideError:
pass
def _usage():
print 'sys.argv[0] [-a] '
sys.exit(0)
if __name__ == '__main__':
import sys
L = []
ln = len(sys.argv)
s = 1
doall = 0
if ln != 5 and ln != 6:
_usage()
if ln == 6:
if sys.argv[1] == '-a':
doall = 1
s += 1
L = [int(sys.argv[s]), int(sys.argv[s+1]), \
int(sys.argv[s+2]), int(sys.argv[s+3])]
eval_24pt(L, doall)
|