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

标签 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 的整数。这里不正确;列表中有元素并没有说明是否会有解决方案(除了可能有)。另请注意,我们在定义用于比较的普遍最小值时遇到了类似的问题……通过建立基准候选,我们可以避免这种情况。

关于python - 请帮助证明代码冗余的合理性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7262876/

相关文章:

python - networkx - 以 block 的形式读取边缘列表(pandas)

python - 维护一个固定大小的堆-python

python - 将 Pandas DataFrame 转换为字典

python - 迭代 ndarray

python - Pandas groupby diff 删除列

javascript - 从网站按钮输出表单收集数据

python - 计算列表元素时区分 0 和 False

python - 在Python中快速计算频率

字符串模板中的 Python 文本换行

python GTK : Scrollable Grid with clickable images