Python beginner's question. Why doesn't aa!=bb!=cc!=dd work?

Asked 2 years ago, Updated 2 years ago, 21 views

while True:
        aa=random.randint(1,10)
        bb=random.randint(1,10)
        cc=random.randint(1,10)
        dd=random.randint(1,10)

        if aa != bb != cc != dd:
            break

Here

if aa!=bb and bb!=cc and aa!=cc and aa! =dd and bb! =dd and cc! =dd: works if aa!=bb!=cc!=dd: Why doesn't it work?

python

2022-09-21 10:54

3 Answers

The reason is that it's a grammar that Python doesn't allow.

It can be used in the form below.

if all([aa != bb, bb != cc, cc != dd]):


2022-09-21 10:54

To give you a little bit of a supplementary explanation,

I'm sure you know all about Python's operators and their priorities.

As you know, != is one of the comparison operators, meaning that the two values are different.

aa != bb != cc != dd

Since we used three identical comparison operators above, the priorities are all the same. So eventually,

((aa != bb) != cc) != dd I'd say it's the same.

For convenience, let's say aa=1, bb=2.

Then aa!=bb will be True.

In other words, it becomes (True!=cc)!=dd.

Cc is a number, so boolean value and !If you compare it with the = operator, it will definitely be True, and

True!= dd is the same.

From the example you posted, I think you wanted to check if each number was different.

If you turn it to the above equation, it will be true, so it will be different from what you intended.


2022-09-21 10:54

You have to do a comparative calculation for all pairs of combinations, and if this is a lot of elements, it's cumbersome and it's missing.

You can also use itertools.combinations and all.

If you compare the number by removing redundancy in a set, there is no fear of missing it.

>>> s = [ 1,2,3,4,5 ]
>>> len(s) == len(set(s))
True
>>> s = [ 1,2,3,4,1 ]
>>> len(s) == len(set(s))
False


2022-09-21 10:54

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.