Last active
February 6, 2019 07:05
-
-
Save rhwlo/479a0b1a685e6953d3cace22c6faf03f to your computer and use it in GitHub Desktop.
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
# 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. | |
# | |
# usage: echo "1 2 3" | python countdown.py | |
from itertools import chain, izip_longest, product, permutations | |
import operator | |
import sys | |
TOLERANCE = 0.6 | |
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 abs(reduce(lambda x, y: _opchoice.pop(0)(x, y), permutation) - solvand) <= TOLERANCE: # :) | |
return (permutation, opchoice) | |
raise NoSolutionException() | |
if __name__ == '__main__': | |
operands = [float(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: {} = {} (more or less)".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