Python: AND评估的优化
Python: optimisation of AND evaluation
在 Python 3 中,我必须检查函数参数中没有发生 3 个条件,因此,我创建了 3 个函数:
def check_lenght(string_id):
# if length is right, return True, otherwise, False
def check_format(string_id):
# return True if some internal format has to be used, in another case, False
def check_case_num(string_id):
# manual iteration to check if certain characters are not contained, return True, otherwise, False
def valid_product_code(id_str):
return check_lenght(id_str) and check_format(id_str) and check_case_num(id_str)
所以,有 3 个函数,其中一个迭代字符串,这是一个潜在的非常繁重的操作。
但是,如果一个函数 return 已经为 False,则没有必要检查其余函数,我们知道逻辑与将 return False,从而能够降低计算成本。
所以,我想知道Python(CPython或其他实现)是否正在优化这个,因此,return check_lenght(id_str) and check_format(id_str) and check_case_num(id_str)
的用法是正确的,还是更好一个一个地检查这些函数,并在第一个函数为 False 时 returning False,有一个更优化但可能不太可读的解决方案。
如何在 Python 中计算此表达式?
我试图通过谷歌搜索以及在此站点中找到此问题的答案
它叫做 short-circuiting
是的,Python 确实支持它:
https://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not
a and b and c
将不会评估 b
或 c
如果 a
已经 returns False
.
x or y
将不会评估 y
如果 x
已经 returns True
.
您会发现几乎所有类 C 语言中的 bool 运算符都是这样工作的。
在 Python 3 中,我必须检查函数参数中没有发生 3 个条件,因此,我创建了 3 个函数:
def check_lenght(string_id):
# if length is right, return True, otherwise, False
def check_format(string_id):
# return True if some internal format has to be used, in another case, False
def check_case_num(string_id):
# manual iteration to check if certain characters are not contained, return True, otherwise, False
def valid_product_code(id_str):
return check_lenght(id_str) and check_format(id_str) and check_case_num(id_str)
所以,有 3 个函数,其中一个迭代字符串,这是一个潜在的非常繁重的操作。 但是,如果一个函数 return 已经为 False,则没有必要检查其余函数,我们知道逻辑与将 return False,从而能够降低计算成本。
所以,我想知道Python(CPython或其他实现)是否正在优化这个,因此,return check_lenght(id_str) and check_format(id_str) and check_case_num(id_str)
的用法是正确的,还是更好一个一个地检查这些函数,并在第一个函数为 False 时 returning False,有一个更优化但可能不太可读的解决方案。
如何在 Python 中计算此表达式?
我试图通过谷歌搜索以及在此站点中找到此问题的答案
它叫做 short-circuiting
是的,Python 确实支持它:
https://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not
a and b and c
将不会评估 b
或 c
如果 a
已经 returns False
.
x or y
将不会评估 y
如果 x
已经 returns True
.
您会发现几乎所有类 C 语言中的 bool 运算符都是这样工作的。