python - 写一个函数,计算如下几个字母代表的数字: AB-CD=EF EF+GH=PPP
巴扎黑
巴扎黑 2017-04-17 17:43:04
0
1
1720

以前找的感觉有缺陷 有0的话就不行了

el = 'AB-CD=EF EF+GH=PPP'
ns = '0123456789'
el = el.replace('=','==').replace(' ', ' and ')
vs = list(set([s for s in el if s>='A' and s<='Z']))
ns = [s for s in ns]
def fs(el, vs, ns):

if not vs:
    if eval(el):
        print el.replace('and ', '').replace('==', '=')
else:
    v = vs[0]
    ix = len(ns)
    while ix:
        ix -= 1
        nel = el.replace(v, ns[ix])
        fs(nel, vs[1:], ns[0:ix]+ns[ix+1:])

import time
st = time.time()
fs(el,vs,ns)
print 'time:%dms'%((time.time()-st)*1000)

后来我又写了一个但太麻烦了 它运行特慢
for A in range(0,10):

for B in range(0,10):
    for C in range(0,10):
        for D in range(0,10):
            for E in range(0,10):
                for F in range(0,10):
                    for G in range(0,10):
                        for H in range(0,10):
                            for P in range(0,10):
                                if ((A*10+B)-(C*10+D)==(E*10+F)and(E*10+F)+(G*10+H)==(P*100+P*10+P)):
                                    if ((A!=B)and(A!=C)and(A!=E)and(A!=F)and(A!=D)and(A!=G)and(A!=H)and(A!=P)and
                                            (B!=C)and(B!=D)and(B!=E)and(B!=F)and(B!=G)and(B!=H)and(B!=P)and
                                            (C!=D)and(C!=E)and(C!=F)and(C!=H)and(C!=G)and(C!=P)and
                                            (D!=F)and(D!=E)and(D!=G)and(D!=H)and(D!=P)and
                                            (E!=F)and(E!=G)and(E!=H)and(E!=P)and
                                            (F!=G)and(F!=H)and(F!=P)and
                                            (G!=H)and(G!=P)):
                                        AB=A*10+B
                                        CD=C*10+D
                                        EF=E*10+F
                                        GH=G*10+H
                                        PPP=P*100+P*10+P
                                        print 'AB-CD=EF:',AB,'-',CD,'=',EF,'EF+GH=PPP',EF,'+',GH,'=',PPP
巴扎黑
巴扎黑

répondre à tous(1)
左手右手慢动作

Question en double : https://segmentfault.com/q/1010000004648870

Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal