简体   繁体   English

Python 中的德摩根定律没有按我认为的那样工作

[英]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 .因此,德摩根定律说not(A and B)not A 或 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.当我输入 a 为 3 和 b 为 5 时,我在 output 中得到 False。 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.两个语句中的 A 和 B 表达式应该相同。 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 .正如您所说,德摩根定律说not(A and B)not A or not B相同。 You are trying not A or not B == not (C and D)您正在尝试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) .让我们首先从容易实现的目标开始:您的陈述实际上并不是在表达not A or not B == not (A and B) ,而是类似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:因此,要测试德摩根定律,您必须确保AB在比较的两侧都相同,例如:

(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)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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