How do I make a program stop when one list or another list is the same as a third list?

Viewed 48

What my goal is is to have a program stop when one of two lists is the same as another list.

I've tried multiple times to do this in different ways, but to no avail.

This is the relevant code:

tower1 = [3, 2, 1]
tower2 = [ ]
tower3 = [ ]

checkl = [3, 2, 1]

if not tower2 == checkl or not tower3 == checkl:
    #move numbers around
else:
    #do something else

Does anyone know how to do what I'm trying to do?

Thanks!

4 Answers

You can use the in operator:

if checkl in (tower2, tower3):
    # do something else
else:
    # move numbers around

Since it's just two lists that you're comparing a list to, you can also chain inequality tests:

if tower2 != checkl != tower3:
    # move numbers around
else:
    # do something else

Lists are equal if the elements at the same indices are equal. Your comparison seems incorrect. It will move numbers around if any of the lists (tower2, tower3) is not equal.

if tower2 == checkl or tower3 == checkl:
    # do something
else:
    # move numbers

Since your request was "a program that stops when one list or another list is the same as a third list", I assume you are thinking of a while loop. Below is a full working code to move numbers around until one between tower2 and tower3 is the same as check1.

import numpy as np

tower1 = [3, 2, 1]
tower2 = [ ]
tower3 = [ ]

checkl = [3, 2, 1]

# keep looping until tower2 == check1 or tower3 == check1
while tower2 != checkl and tower3 != checkl:
    print('tower2:', tower2, '; tower3:', tower3, '--> keep looping')
    if tower2 != checkl and tower3 != checkl:
        # move numbers around
        tower2 = list(np.random.permutation([1, 2, 3]))
        tower3 = list(np.random.permutation([1, 2, 3]))
    else:
        # stop the program
        break

print('tower2:', tower2, '; tower3:', tower3, '--> done!')

Output:

tower2: [] ; tower3: [] --> keep looping
tower2: [1, 2, 3] ; tower3: [2, 1, 3] --> keep looping
tower2: [1, 3, 2] ; tower3: [2, 3, 1] --> keep looping
tower2: [2, 3, 1] ; tower3: [2, 3, 1] --> keep looping
tower2: [3, 2, 1] ; tower3: [3, 1, 2] --> done!
Related