gpt4 book ai didi

python - 给定 2 个 int 值,如果一个是负数,另一个是正数,则返回 True

转载 作者:IT老高 更新时间:2023-10-28 22:21:19 28 4
gpt4 key购买 nike

def logical_xor(a, b): # for example, -1 and 1
print (a < 0) # evaluates to True
print (b < 0) # evaluates to False
print (a < 0 != b < 0) # EVALUATES TO FALSE! why??? it's True != False
return (a < 0 != b < 0) # returns False when it should return True

print ( logical_xor(-1, 1) ) # returns FALSE!

# now for clarification

print ( True != False) # PRINTS TRUE!

有人可以解释发生了什么吗?我正在尝试制作一个衬里:

lambda a, b: (a < 0 != b < 0)

最佳答案

Python 中的所有比较运算符都有 same precedence.此外,Python 会进行链式比较。因此,

(a < 0 != b < 0)

分解为:

(a < 0) and (0 != b) and (b < 0)

如果其中任何一项为假,则表达式的总结果将为 False

您要做的是分别评估每个条件,如下所示:

(a < 0) != (b < 0)

其他变体,来自评论:

(a < 0) is not (b < 0) # True and False are singletons so identity-comparison works

(a < 0) ^ (b < 0) # bitwise-xor does too, as long as both sides are boolean

(a ^ b < 0) # or you could directly bitwise-xor the integers;
# the sign bit will only be set if your condition holds
# this one fails when you mix ints and floats though

(a * b < 0) # perhaps most straightforward, just multiply them and check the sign

关于python - 给定 2 个 int 值,如果一个是负数,另一个是正数,则返回 True,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29790594/

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