gpt4 book ai didi

python - 在 python 中使用德摩根定律有什么好处吗?

转载 作者:太空狗 更新时间:2023-10-29 21:13:00 25 4
gpt4 key购买 nike

我使用 pycharm 并且在使用 if 语句时有几次我看到了使用 De Morgan 定律更改语句的建议,例如以下 if 语句:

if new_odds > 10 and new_odds <= 30:

if not (not (new_odds > 10) or not (new_odds <= 20)):

对我来说,这会降低它的可读性,那么使用德摩根定律是否有任何优势,还是完全是个人选择?

最佳答案

De Morgan's laws声明:

"not (A and B)" is the same as "(not A) or (not B)"

and also,

"not (A or B)" is the same as "(not A) and (not B)"

用于在替代形式之间转换逻辑。因此,虽然您所做的转换符合德摩根定律,但它变得更难阅读了。正如其他人所建议的那样简单得多 10 < new_odds <= 30将更具可读性,但是了解这是 10 < new_odds and new_odds <= 30 的缩写非常重要因为,从这里开始你可以做这样的逻辑:

10 < new_odds <= 30 != max_odds | default_condition

扩展为:

10 < new_odds and new_odds <= 30 and 30 != max_odds and max_odds | default_condition

考虑到语法糖,让我们看另一个例子:

我们将在简单的角色扮演游戏中考虑一个人为的例子,我们将在其中查看我们称为“荷兰勇气”的技能。这种攻击的前提是,如果你处于最大生命值,并且你的护甲或攻击等级不足以攻击敌人,你可以获得加成。我需要知道这条规则何时不适用。

写出来我们有 4 个条件:

A = health == max_health
B = armor > enemy.attack
C = attack > enemy.defense
no_bonus = not(A and not(B and C))

使用 De Morgan 定律,我可以将其分解为:

not(A and not(B and C))
not(A) or not(B and C)
not(A) or not(B) or not(C)
not(health == max_health) or not(armor > enemy.attack) or (attack > enemy.defense)

好吧,现在我可以进一步分解...

health < max_meath or armor < enemy.attack < attack > enemy.defense

这里我们假设与== max_health相反是< max_health否则它不是最大值。

虽然做作,但这向我们表明德摩根定律是一种使我们能够重写逻辑的工具。这种逻辑是否得到改进取决于程序员,但目的是能够生成更简单的结构,首先是更具可读性,其次希望需要的指令更少,因此速度更快。

关于python - 在 python 中使用德摩根定律有什么好处吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21320961/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com