Last active
August 29, 2015 14:19
-
-
Save mmirz719/dd7fff2990fa41c9f833 to your computer and use it in GitHub Desktop.
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
# look, it's art. okay? it's art about how functional programming in Python is sometimes ugly | |
# | |
# it just so happens this art has a terrible worst-case complexity. | |
# | |
from itertools import chain, izip_longest, product, permutations | |
import operator | |
import sys | |
operators = (operator.add, operator.sub, operator.mul, operator.truediv) | |
READABLE_OPERATORS = { | |
operator.add: "+", | |
operator.sub: "-", | |
operator.mul: "*", | |
operator.truediv: "/" | |
} | |
class NoSolutionException(Exception): pass # let's be civilized here | |
def solve(operands, solvand): | |
for opchoice in product(operators, repeat=(len(operands) - 1)): | |
# wasn't sure if order of operands is meant to matter, so I'll increase | |
# the worst-case complexity a bit. | |
# | |
# I mean, it wasn't a fast solution to start with ... | |
for permutation in permutations(operands): | |
_opchoice = list(opchoice) | |
if reduce(lambda x, y: _opchoice.pop(0)(x, y), permutation) == solvand: # :) | |
return (permutation, opchoice) | |
raise NoSolutionException() | |
if __name__ == '__main__': | |
operands = [int(token) for token in sys.stdin.read().split(' ')] | |
solvand = operands.pop(-1) | |
try: | |
permutation, opchoice = solve(operands, solvand) | |
# this next bit is my favorite <3 | |
print "solution: {} = {}".format(" ".join(chain(*izip_longest(map(str, permutation), | |
map(READABLE_OPERATORS.get, opchoice), fillvalue=''))), | |
solvand) | |
except NoSolutionException: | |
print "Invalid" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment