Created
September 4, 2018 11:36
-
-
Save Anthchirp/52bf057bea22fa4ee501bd6ca24c78c1 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 absolute_import, division, print_function | |
import itertools | |
import operator | |
ops = {operator.add: '+', operator.sub: '-', operator.mul: '*', operator.truediv: '/'} | |
def run(a, b, c, d, op1, op2, op3, order): | |
try: | |
if order == 1: | |
return op1(a, op2(b, op3(c, d))) | |
elif order == 2: | |
return op1(a, op3(op2(b, c), d)) | |
elif order == 3: | |
return op3(op2(op1(a, b), c), d) | |
elif order == 4: | |
return op3(op1(a, op2(b, c)), d) | |
elif order == 5: | |
return op2(op1(a, b), op3(c, d)) | |
except ZeroDivisionError: | |
return None | |
brackets = { | |
1 : (' ', ' ', ' (', ' ', ' (', ' ', ' ', '))'), | |
2 : (' ', ' ', ' ((', ' ', ' ', ') ', ' ', ')'), | |
3 : ('((', ' ', ' ', ') ', ' ', ') ', ' ', ''), | |
4 : (' (', ' ', ' (', ' ', ' ', ')) ', ' ', ''), | |
5 : ('((', ' ', ' ', ') ', ' (', ' ', ' ', '))'), | |
} | |
def find_all(target): | |
count = 0 | |
for a, b, c, d in itertools.permutations((1,3,4,6)): | |
for op1, op2, op3 in itertools.product(ops, ops, ops): | |
for order in (1,2,3,4,5): | |
result = run(a, b, c, d, op1, op2, op3, order) | |
if result is not None and abs(result - target) < 0.01: | |
count = count + 1 | |
print("{count:3d}. {p[0]}{a}{p[1]}{op1}{p[2]}{b}{p[3]}{op2}{p[4]}{c}{p[5]}{op3}{p[6]}{d}{p[7]} = {result}".format(count=count, result=result, a=a, b=b, c=c, d=d, op1=ops[op1], op2=ops[op2], op3=ops[op3], p=brackets[order])) | |
find_all(24) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment