Created
February 8, 2014 20:36
-
-
Save dfeng/8889898 to your computer and use it in GitHub Desktop.
Derek's 93
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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