在我正在阅读的《实用编程 - 使用 Python 的计算机科学简介》一书中,我遇到了一个代码示例。我可以看到第一个周期和条件检查的原因是什么。在我看来,仅第二个周期就足以完成相同的工作。我已经通过调试器调试了代码,但仍然无法找出我认为无用的部分的原因。
def largest_below_threshold(values, threshold):
'''Find the largest value below a specified threshold. If no value is
found, returns None.'''
result = None
#the first cycle
for v in values:
if v < threshold:
result = v
break
#the conditional check
if result is None:
return None
#the second cycle
for v in values:
if result < v < threshold:
result = v
return result
谢谢!
最佳答案
两者兼有的原因是,在一般情况下,您必须首先确定某个合适元素的存在,然后才能询问是否存在最佳元素。在此代码中,第一个循环确定了合适元素的存在,然后第二个循环可以假定这一点并简单地寻找最佳元素。
要更改第二个循环以使其完成第一个循环的工作,可以这样做:
def largest_below_threshold(values, threshold):
'''Find the largest value below a specified threshold. If no value is
found, returns None.'''
result = None
#the second cycle
for v in values:
if v < threshold:
if result is None:
result = v
elif result < v:
result = v
return result
请注意,要找到例如一组整数中最大的整数,你不需要第一遍,因为它保证会有一个整数 n 使得列表中没有任何大于 n 的整数。这里不正确;列表中有元素并没有说明是否会有解决方案(除了可能有)。另请注意,我们在定义用于比较的普遍最小值时遇到了类似的问题……通过建立基准候选,我们可以避免这种情况。
关于python - 请帮助证明代码冗余的合理性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7262876/