Skip to content

Instantly share code, notes, and snippets.

@dfeng
Created February 8, 2014 20:36
Show Gist options
  • Save dfeng/8889898 to your computer and use it in GitHub Desktop.
Save dfeng/8889898 to your computer and use it in GitHub Desktop.
Derek's 93
import itertools
# using reverse polish notation
def calculate(expr):
stack = list()
for e in expr:
if type(e) == int:
stack.append(e)
else:
b, a = stack.pop(), stack.pop()
if e == "+":
stack.append(a + b)
elif e == "-":
stack.append(a - b)
elif e == "*":
stack.append(a * b)
elif e == "/":
if b == 0:
return float(-0.5) # hack
stack.append(a / float(b))
return float(stack[0])
def solve():
solns = list()
for nums in itertools.combinations(range(1,10), 4):
ans = list()
for combs in itertools.permutations(nums, 4):
for opss in itertools.combinations_with_replacement(("+", "-", "*", "/"), 3):
for ops in itertools.permutations(opss, 3):
poss = [
combs + ops,
combs[:3] + (ops[0], ) + (combs[3], ) + ops[1:],
combs[:3] + ops[:2] + (combs[3], ) + (ops[2], ),
combs[:2] + (ops[0], ) + (combs[2], ) + (ops[1], ) + (combs[3], ) + (ops[2], ),
combs[:2] + (ops[0], ) + combs[2:] + ops[1:]
]
for p in poss:
res = calculate(p)
if res.is_integer():
ans.append(int(res))
# finding the highest consecutive in the list
for x in xrange(1, (max(ans)+2)):
if x not in ans:
solns.append(((x-1), nums))
break
return solns
print max(solve())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment