[英]python: best way to verify conditions and raise Exception
hi i have to verify if a vector contains all 0 or 1 and if not raise exception: 嗨,我必须验证一个向量是否包含全0或1,如果没有引发异常:
def assert_all_zero_or_one(vector):
if set(vector)=={0}: return 0
if set(vector)=={1}: return 1
raise TypeError
with this exceution 有了这个优点
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.. there is a best way to do it with python? 我不喜欢这个解决方案..用python有一个最好的方法吗?
I think your solution conveys your intent well. 我认为您的解决方案很好地传达了您的意图。 You could also do 你也可以这样做
def assert_all_zero_or_one(vector):
if set(vector) not in ({0}, {1}): raise TypeError
return vector[0]
so you build set(vector)
only once, but I think yours is easier to understand. 所以你只建立一次set(vector)
,但我认为你的更容易理解。
How's this? 这个怎么样?
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
Reads quite nicely, I think. 我认为读得很好。
If you prefer short and cryptic: 如果你喜欢简短和神秘:
def assert_all_zero_or_one(vector):
a, = set(vector)
return a
Although that gives you a ValueError rather than a TypeError. 虽然这给你一个ValueError而不是TypeError。
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])))
You can also do something like this. 你也可以这样做。
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")
def assert_all_zero_or_one(vector):
if len(vector) == sum(vector):
return True
elif sum(vector) == 0:
return True
return False
This should work nicely. 这应该很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.