简体   繁体   中英

De Morgan's law in Python not working as I think it should

So, De Morgan's law says that not(A and B) is the same as not A or not B . When I tried to implement it using this code, it does not work. When I input a to be 3 and b to be 5, I get False in the output. What am I missing and how to do it the right way?

a = int(input("First num: "))
b = int(input("Second num: "))

print((not (a > 3) or not (b > 7))   ==  (not ((a <= 3) and (b <= 7 )) )  )

A and B expressions in both statements should be the same. Try changing

print((not (a > 3) or not (b > 7))   ==  (not ((a <= 3) and (b <= 7 )) )  )

to

print((not (a > 3) or not (b > 7))   ==  (not ((a > 3) and (b > 7 )) )  )

As you said, De Morgan's law says that not(A and B) is the same as not A or not B . You are trying not A or not B == not (C and D)

This is DeMorgan's law.

a = int(input("First num: "))
b = int(input("Second num: "))

print((not (a > 3) or not (b > 7))==  (not ((a > 3) and (b > 7))))

Let's start with the low hanging fruit first: your statement is not actually expressing not A or not B == not (A and B) , but rather something like not C or not D == not (A and B) .

So, to test De Morgan's law, you would have to make sure that both A and B are the same on both sides of the comparison, for example:

(not (a <= 3) or not (b <= 7)) == (not ((a <= 3) and (b <= 7)))

Now, interestingly enough, the following two statements also hold:

not (a <= 3) == (a > 3)
not (b <= 7) == (b > 7)

So, alternatively, you could test the following:

((a > 3) or (b > 7)) == (not ((a <= 3) and (b <= 7)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM