python – 请帮助证明代码冗余的合理性

在我正在阅读的书“实用编程 – 使用
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的整数.这不正确;列表中的元素没有说明是否会有解决方案(除了可能存在).另请注意,我们在此处也存在类似的问题,即为比较定义通用的最小值…通过建立基线候选,我们可以避免.

点赞