有没有其他方法可以在Python中编写多个条件?

时间:2019-09-30 03:17:03

标签: python python-3.x cryptarithmetic-puzzle

我是python的新手,我做的是2 + 2 = 4,其中每个字母代表1-10之间的不同数字。我需要找到所有组合。我想知道是否有更好的书写方式,尤其是“ if”和“ for”

for t in range (1,10):
  for f in range (1,10):
    for w in range(10):
      for o in range(10):
        for u in range(10):
          for r in range(10):
            if 2*(t*100 + w*10 + o) == f*1000 + o*100 + u*10 + r and t is not f and t is not w and t is not o and t is not u and t is not r and f is not w and f is not o and f is not o and f is not u and f is not r and w is not o and w is not u and w is not r and o is not u and o is not r and u is not r:
              print(t,w,o, "and", f,o,u,r)

我尝试过这样写,但是它给了我7个以上的结果

if 2*(t*100 + w*10 + o) == f*1000 + o*100 + u*10 + r and t != f != w != o != u != r

3 个答案:

答案 0 :(得分:1)

您可以使用这样的简单技巧:

for t in range (1,10):
  for f in range (1,10):
    for w in range(10):
      for o in range(10):
        for u in range(10):
          for r in range(10):
            if 2*(t*100 + w*10 + o) == f*1000 + o*100 + u*10 + r and len(set([t,f,w,o,u,r])) == 6:
              print(t,w,o, "and", f,o,u,r)

想法是set仅存储不同的数字,因此,如果它们成对地不同,则集合的长度应等于变量的数量

答案 1 :(得分:1)

您可以使用itertools.product

for t, f, w, o, u, r in itertools.product(range(1, 10), range(1, 10), range(10), range(10), range(10), range(10)):

如果您不想重复所有的ranges,可以这样做:

for t, f, w, o, u, r in itertools.product(*([range(1, 10)]*2 + [range(10)]*4)):

但说实话,它的可读性较差。

答案 2 :(得分:0)

聪明地工作,而不是艰苦=)

for t in range (1,10):
  for f in range (1,10):
    if f == t : continue
    for w in range(10):
      if w in [t,f] : continue
      for o in range(10):
        if o in [t,f,w] : continue
        for u in range(10):
          if u in [t,f,w,o] : continue
          for r in range(10):
            if r in [t,f,w,o,u] : continue
            if 2*(t*100 + w*10 + o) == f*1000 + o*100 + u*10 + r :
              print(t,w,o, "and", f,o,u,r)

这将为您节省很多不必要的迭代。