Last active
August 29, 2015 14:25
-
-
Save rynorris/d81f607889a949081bac 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
from __future__ import division | |
from itertools import permutations | |
def solve(nums, target): | |
ops = [("+", lambda x,y: x+y), | |
("/", lambda x,y: x/y), | |
("*", lambda x,y: x*y), | |
("-", lambda x,y: x-y)] | |
closest = 1000 | |
curr_op = "" | |
best_solution = [] | |
# Update closest based on numbers in the list, we might be done already. | |
for n in nums: | |
closest = min(closest, abs(target - n)) | |
if closest == 0: | |
return (closest, best_solution) | |
# Remove any zeros, they are useless. | |
nums = filter(lambda x: x != 0, nums) | |
# Choose two numbers to combine, then recursively call in for each possible | |
# operation. | |
for x, y in permutations(nums, 2): | |
new_nums = nums[:] | |
new_nums.remove(x) | |
new_nums.remove(y) | |
for op in ops: | |
new_val = op[1](x,y) | |
if int(new_val) != new_val: | |
continue | |
curr_op = "{0} {1} {2} = {3}".format(x, op[0], y, new_val) | |
(score, soln) = solve(new_nums + [op[1](x,y)], target) | |
if score < closest: | |
closest = score | |
best_solution = [curr_op] + soln | |
if closest == 0: | |
return (closest, best_solution) | |
return (closest, best_solution) | |
if __name__ == "__main__": | |
closest, soln = solve([75, 50, 25, 100, 5, 6], 893) | |
for l in soln: | |
print l |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment