Python: best way to check conditions and raise exception

hi, I have to check if the vector contains all 0 or 1 and if no exception occurs:

def assert_all_zero_or_one(vector):
    if set(vector)=={0}: return 0
    if set(vector)=={1}: return 1
    raise TypeError

with this exception

assert_all_zero_or_one([1,1,1]) # return 1
assert_all_zero_or_one([0,0]) # return 0
assert_all_zero_or_one([1,0,1]) # raise TypeError

I don't like this solution .. is there a better way to do this with python?

+3
source share
5 answers
def allOneOf(items, ids):
    first = items[0]
    if first in ids and all(i==first for i in items):
        return first
    else:
        raise TypeError()

assert_all_zero_or_one = (lambda vector: allOneOf(vector, set([0,1])))
+3
source

I think your decision conveys your intentions well. You can also do

def assert_all_zero_or_one(vector):
    if set(vector) not in ({0}, {1}): raise TypeError
    return vector[0]

so you set(vector)only create once, but I think yours is easier to understand.

+4
source

?

def assert_all_zero_or_one(vector):
    if all(v==1 for v in vector): return 1
    elif all(v==0 for v in vector): return 0
    else: raise TypeError

, .

:

def assert_all_zero_or_one(vector):
    a, = set(vector)
    return a

ValueError, TypeError.

+4

- .

import functools
import operator

def assert_all_zero_or_one(vector):
    if ((functools.reduce(operator.__mul__,vector) == 1) or (functools.reduce(operator.__add__,vector) == 0)):
            return vector[0]
    else:   
        raise TypeError("Your vector should be homogenous")
+1
def assert_all_zero_or_one(vector):
    if len(vector) == sum(vector):
        return True
    elif sum(vector) == 0:
        return True
    return False

.

0

Source: https://habr.com/ru/post/1792492/


All Articles