简体   繁体   English

带状态运算符的3状态3输入功能未产生预期的结果

[英]3 state, 3 input function with bitwise operators does not produce expected result

This is some code that I wrote up to generate a set of numbers; 这是我编写的用于生成一组数字的一些代码。

def _tnry(x,y,z):
    a = None

    if((y == 0 & z == 0) | (x == 0 & y == 0) | (x == 0 & z == 0)):
        a = 1

    if((y == 1 & z == 1) | (x == 1 & y == 1) | (x == 1 & z == 1)):
        a = 2

    if((y == 2 & z == 2) | (x == 2 & y == 2) | (x == 2 & z == 2)):
        a = 0

    print(x,y,z,'ternary =',a )

I am having some problems with the output when you give the input of the following: 当您输入以下内容时,输出出现问题:

_tnry(0,1,2)
_tnry(0,2,1)
_tnry(1,0,2)
_tnry(1,2,0)
_tnry(2,0,1)
_tnry(2,1,0)

As far as I can see in my code a should not ever come out as being equal to 0, 1 or 2. I want to force it to always be None in the examples given. 据我在代码中看到的, a永远不会等于0、1或2。我想在给出的示例中强制将其始终设置为None

All other output from the script is how I want it to come out. 脚本的所有其他输出就是我希望它输出的方式。

Bitwise operators & have higher precedence over other operators, so 按位运算符&优先于其他运算符,因此

y == 0 & z == 0

is actually interpreted as 实际上被解释为

y == (0 & z) == 0

Which ends up becoming 最终成为

y == 0 == 0

Which is different from what you want. 这与您想要的不同。 This applies to all your conditions. 这适用于您的所有条件。

You'll want to fix this by using another layer of parens: 您将需要使用另一层parens来解决此问题:

(y == 0) & (z == 0)

Here's a shorter and easier-to-debug, although maybe less clear, way to approach it (assumes all inputs are 0,1, or 2, and that you do in fact mean or and and rather than bitwise): 这是一种更短且更容易调试的方法,尽管可能不太清楚,但它的处理方式(假设所有输入均为0,1或2,并且您实际上是按orand而不是按位进行操作):

def _tnry(x,y,z):

    if len({x,y,z}) < 3: #at least two are the same:
        return (sorted([x,y,z])[1] + 1) % 3

If at least two are the same, then the middle one when they're sorted will be from the majority. 如果至少两个相同,则排序时中间的一个将来自多数。 Returns None by default, like all Python functions. 像所有Python函数一样,默认情况下返回None。

use and for logical and. 使用and表示逻辑与。

def _tnry(x,y,z):
    a = None
    if((y == 0 and z == 0) | (x == 0 and y == 0) | (x == 0 and z == 0)):
        a = 1
    if((y == 1 and z == 1) | (x == 1 and y == 1) | (x == 1 and z == 1)):
        a = 2
    if((y == 2 and z == 2) | (x == 2 and y == 2) | (x == 2 and z == 2)):
        a = 0
    print(x,y,z,'ternary =',a )

if there's no need to constrain the input to 0,1,2 I would write it like this: 如果不需要将输入限制为0,1,2,我会这样写:

def _tnry(x,y,z):
    if y == z or x == z :
        a = z
    elif x == y : 
        a = x
    else:
        a = None
    print(x,y,z,'ternary =',a )

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

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