Created
December 8, 2011 23:21
-
-
Save jordanorelli/1449206 to your computer and use it in GitHub Desktop.
some homework assignment for some freshman kid on reddit.
This file contains hidden or 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
# 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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.