简体   繁体   中英

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.

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:

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

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.

use and for logical 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:

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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