import itertools
import re
operator = ['+','-','*','/']
format = ['((%d%s%d)%s%d)%s%d',
'(%d%s%d)%s(%d%s%d)',
'(%d%s(%d%s%d))%s%d',
'%d%s((%d%s%d)%s%d)',
'%d%s(%d%s(%d%s%d))']
def combine (numlist,oplist=operator):
expre=[]
for ii in list(itertools.permutations(numlist,len(numlist))):
for jj in list(itertools.product(oplist,repeat=3)):
expre.append(Turn(list(ii),list(jj)))
return expre
def Turn(num,letter):
result=[]
for i in range(len(num)):
result.append(num[i])
try:
result.append(letter[i])
except IndexError:
pass
return result
def GetExpression(numlist,target,form=format):
expre=set()
exall=combine(numlist)
for ex in exall:
for fm in form:
try:
exp=str(fm)%tuple(ex)
if eval(exp)==target:
expre.add(exp)
except ZeroDivisionError:
pass
return expre
def NumOperator(str):
save=[]
start=''
for sr in str:
try:
int(sr)
start+=sr
except ValueError:
if start=='':
save.append(sr)
else:
save.append(start)
save.append(sr)
start=''
if start!='':
save.append(start)
return save
def Simple(exprelist):
simple=[]
Last=[]
for ex in exprelist:
sr=ex
p=re.findall("\([^()+]\)",ex)
for ii in p:
ex=ex.replace(ii,str(eval(ii)))
simp=NumOperator(ex)
if sorted(simp) not in simple:
simple.append(sorted(simp))
Last.append(sr)
return Last
for j in list(Simple(GetExpression([11,3,5,1],24))):
print ('%s = %s'% (j,eval(j)))
>>> (11-5)*(1+3) = 24
为什么和老师一样的代码,但运行结果却只有一个啊?求老师解答!!!
def NumOperator(str):
save=[]
start=''
for sr in str:
try:
int(sr)
start+=sr
except ValueError:
if start=='':
save.append(sr)
else:
save.append(start)
save.append(sr)
start=''
if start!='':
save.append(start)
return save
请问这个NumOperator方法将表达式4*6转化为字符集的['4','6','*']的原理是什么啊?初学者求大神解答!
p=re.findall("\([^()+]\)",ex)应改为 p=re.findall("\([^()]+\)",ex),太粗心了?