Skip to content

Instantly share code, notes, and snippets.

@jordanorelli
Created December 8, 2011 23:21
Show Gist options
  • Save jordanorelli/1449206 to your computer and use it in GitHub Desktop.
Save jordanorelli/1449206 to your computer and use it in GitHub Desktop.
some homework assignment for some freshman kid on reddit.
# Given a list of numbers, write in increasing order all the integers you can
# obtain using each number once and any combination of addition,
# multiplication, division, and subtraction.
from itertools import permutations, product
from operator import add, mul, div, sub
solutions = set()
funcs = [add, mul, div, sub]
seeds = [22,71,13,1]
def polish(tokens):
stack = []
for token in tokens:
if callable(token):
stack.append(token(stack.pop(), stack.pop()))
else:
stack.append(token)
return stack[0]
for operators in product(funcs, repeat=len(seeds)-1):
for tokens in permutations(seeds + list(operators)):
try:
solutions.add(polish(tokens))
except (IndexError, ZeroDivisionError):
pass
print sorted(solutions)
@jordanorelli
Copy link
Author

a token list will raide an IndexError if the ordering isn't right, e.g., if you say 1 1 + + + 2 2 it's invalid. You get a ZeroDivisionError if you... divide by zero.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment