gpt4 book ai didi

python - 简洁的书写方式(a + b == c 或 a + c == b 或 b + c == a)

转载 作者:IT老高 更新时间:2023-10-28 12:29:59 26 4
gpt4 key购买 nike

有没有更简洁或者pythonic的方式来编写 boolean 表达式

a + b == c or a + c == b or b + c == a

我想出了

a + b + c in (2*a, 2*b, 2*c)

但这有点奇怪。

最佳答案

如果我们看一下 Python 之禅,请强调我的:

The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than right now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

最 Pythonic 的解决方案是最清晰、最简单、最容易解释的解决方案:

a + b == c or a + c == b or b + c == a

更好的是,您甚至不需要了解 Python 即可理解此代码!这很容易。这是毫无保留的最佳解决方案。其他任何东西都是智力手淫。

此外,这也可能是性能最好的解决方案,因为它是所有短路提案中唯一的一个。如果a + b == c,只进行一次加法和比较。

关于python - 简洁的书写方式(a + b == c 或 a + c == b 或 b + c == a),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32085675/

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