-2

I want to create two random sets and compare them to two other sets. The programm should stop when both sets are the same as the other two sets. This is a boiled down version of the code i'm having trouble with:

import random
random.seed()

a = set()
b = set()
c = set()
d = set()

for i in range(3):
    a.add(random.randint(1,10))
    b.add(random.randint(1,10))

while a!=c and b!=d:
    c.clear()
    d.clear()
    for i in range(3):
        c.add(random.randint(1,10))
        d.add(random.randint(1,10))

print(a,b)
print(c,d)

The exact line with my problem: while a!=c and b!=d:

With "and" the loop already stops when just one pair of sets are the same. When i switch the "and" for "or" it does exacly what i want, i just don't understand why? Can somebody please explane.

ozboss
  • 3
  • 5

4 Answers4

2

The condition holds when both a is not c and b is not d. As soon as one pair is equal then the and fails and the loop is broken.

As you have identified you could use an or which will work, but it may be more clear to use:

while not (a == c and b == d):
    ...

which works exactly how you would say it!

Joe Iddon
  • 20,101
  • 7
  • 33
  • 54
1

Think about it. You have the condition:

a != c and b != d

What exactly is this condition telling Python? Well, we can see it uses the and operator. The and operator will only return True, if both of its conditions are true. From this, we can see that the above condition will only return true if both the a set is not equal to the c set and the b set is not equal to the d set.

So what would happen when one pair of sets becomes equal? The above condition will fail. Since one of the comparisons between two sets would return False, rather than True, and will also return false, since both of its conditions are not true.

What you actually want is this:

not (a == c and b == d)

I'll leave it as an exercise up to you to figure why the above condition works, whereas a != c and b != d does not.

Christian Dean
  • 22,138
  • 7
  • 54
  • 87
0

While loops repeat when the statement is True, in this case when either a != c orb != devaluates to False, so will the while loop argument. You want to alter the logic, change:

a != c and b !=d

to:

not (a == c and b == d)

or:

a != c or b != d

This will achieve what you are after.

0

You might try:

while not (a == c and b == d):
    #code
Vendetta
  • 2,078
  • 3
  • 13
  • 31