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
26
27
# 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.
from itertools import permutations as pm, product as pd
mx=100**4
num,tg=[1,2,3,4,5,6],999 #(closer: 960)
add,mul,sub=lambda x,y:x+y,lambda x,y:x*y,lambda x,y:x-y
div=lambda x,y:x//y if (y and not x%y) else mx
pops={add:"+",mul:"*",sub:"-",div:"/"}
def mv(ops,n,res,conc,r): # Evals or prints
for i in range(r):
res=conc(ops[i],n[i],res)
return(res)
def solve():
best,opb,numb,dlt=num[-1],[],num,tg+num[-1]
for r in range(len(num)): # All # numbers
for nc in pm(num,r+1): # All permz(nb)
for opv in pd(pops.keys(),repeat=r): # ops
res=mv(opv,nc,nc[-1],lambda f,x,y:f(x,y),r)
if abs(res-tg)<dlt:
bes,opb,numb,rb=res,opv,nc,r
dlt=abs(res-tg)
print(bes,"=",mv(opb,numb,str(numb[-1]),lambda f,x,y:"("+str(x)+pops[f]+str(y)+")",rb)[1:-2])
solve()
Enter to Rename, Shift+Enter to Preview
OUTPUT
Run