PY
py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# Le compte est bon ! VcC 2017
# How to reach N with given numbers & +-/* operators (or the closest possible solution)
# Restart if you reach time limit or use less num or pops
from itertools import permutations as pm, product as pd
from operator import add,mul,sub,truediv as div
O={add:"+",mul:"*",sub:"-",div:"/"}
ev=lambda f,x,y:f(x,y)
pr=lambda f,x,y:"({}{}{})".format(x,op[f],y)
def mv(f,ops,res,*n): # Evals or prints
for o,x in zip(ops,n):
try: res=f(o,x,res)
except: return(10**9)
return(res)
# Solving with num,tg
N,T=[7,3,4,5,6],999 #(closer: 990)
b,o,m=min(((e,o,c) for r in range(len(N)) for c in pm(N,r+1) for o in pd(O.keys(),repeat=r) for e in [mv(ev,o,*c)]),key=lambda v:abs(v[0]-T))
print(b,"=",mv(pr,o,*m))
# Evaluation example
print(mv(ev,[add,mul,sub],1,2,3,4))
print(mv(pr,[add,mul,sub],1,2,3,4))
Enter to Rename, Shift+Enter to Preview
OUTPUT
Run