Search code examples
pythonpython-3.xcryptarithmetic-puzzle

Is there a different way to write multiple conditions in Python?


I'm new to python, I am doing the TWO + TWO = FOUR, where each letter represents a different number from 1-10. I need to find all combinations. I was wondering if there is a better way to write it, especially 'if' and '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)

I've tried writing it like this but it gave me more than 7 results

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

Solution

  • Work smart, not hard =)

    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)
    

    This will save you a lot of unnecessary iterations.