Last active
August 23, 2020 20:24
-
-
Save shayelkin/736f143cb4f7d2310c5b to your computer and use it in GitHub Desktop.
11 lines solution for https://www.thumbtack.com/engineering/pycon-2015/, based on https://gist.github.com/shayelkin/2397850f9b2c3df7e3aa (please excuse the golfing, I'm aiming for length)
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 operator, itertools | |
def inspiration(*nums): | |
assert all(isinstance(x, int) and x > 0 for x in nums), "a deck of cards contains only integers" | |
ops = {operator.add: '+', operator.sub: '-', operator.mul: '*', operator.div: '/'} | |
possibilities = {reduce(lambda v, t: t[0](v,t[1]), zip(o, n[1:]), n[0]): (n, o) \ | |
for n in itertools.permutations(nums[:-1]) for o in itertools.product(ops.keys(), repeat=len(nums)-2)} | |
try: | |
result_nums, result_ops = possibilities[nums[-1]] | |
return ' '.join('%s %s' % x for x in zip(result_nums, (ops[o] for o in result_ops))) + ' %s' % str(result_nums[-1]) | |
except KeyError: | |
return None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment