user9654395
user9654395

Reputation: 109

How to handle bool arguments to a function?

Question is:
Compose a function odd() that takes three bool arguments and returns True if an odd number of arguments are True, and False otherwise.

For example, the output is:

>>> odd ( False , True , False )
True
>>>
>>> odd ( True , True , True )
True
>>>
>>> odd ( True , True , False )
False

This is question but I am not sure what I write as argument in function? def bool(x,y,z) is it right? By the way, I tried one way to solve that question.

import sys

def bool(x,y,z):
    if x+y+z%2==0:
        return False
    else:
        return True

a = int(sys.argv[1])
b = int(sys.argv[2])
c = int(sys.argv[3])

m = bool(a,b,c)

print(m)

My way is very bad I know, but I am confused about boolean argument. Are there anyone to show me a way?

Upvotes: 0

Views: 3039

Answers (3)

hiro protagonist
hiro protagonist

Reputation: 46849

operator precendence evaluates x+y+z%2 as x+y+(z%2). what you want is (x+y+z)%2. (and bool is a built-in type; you should call your function something other than that...)

the function you are looking for is called parity function .

if you accept bool as input type you might just xor (^) the three variables:

def odd(b0, b1, b2):
    return b0 ^ b1 ^ b2

tested with

from itertools import product

for b0, b1, b2 in product((True, False), repeat=3):
    print('odd({}, {}, {}) = {}'.format(b0, b1, b2, odd(b0, b1, b2)))

this could be generalized to accept an arbitrary number of arguments:

from operator import xor
from functools import reduce

def odd(*bools):
    return reduce(xor, bools, False)

Upvotes: 3

timgeb
timgeb

Reputation: 78650

Your approach is ok, you just forget parentheses.

def odd(x, y, z):
    return bool((x + y + z)%2)

You could easily extend this function to take an arbritrary number of arguments:

def odd(*bools):
    return bool(sum(bools)%2)

Upvotes: 3

Vasilis G.
Vasilis G.

Reputation: 7846

You can simplify your function by removing if and else conditions and just write:

def boolean(x,y,z):
    return (x + y + z) % 2 == 1

print(boolean(False, False, False))   
print(boolean(False, False, True))
print(boolean(False, True, True))
print(boolean(True, True, True))

Output:

False
True
False
True

Also, you shouldn't use the name bool as a function name as it is a Python keyword. Try using a different one.

Upvotes: 1

Related Questions