开发者

Please help to justify the code redundancy

In the book I'm reading now, Practical Programming - An Introduction to Computer Science Using Python, I've come across an example of code. I can's see what is the reason for the first cycle and the conditional check. As I see it, the second cycle alone is enough to do the same work. I've put the code through the debugger, but still can't figure out the reason for the parts I consider useless.

def largest_below_threshold(values, threshold):
'''Find the largest value below a specified threshold. If no v开发者_JAVA技巧alue 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

Thanks!


The reason for having both is that you must first establish the existence of some suitable element, in the general case, before you can ask whether a best one exists. In this code, the first loop establishes the existence of a suitable element, and the second loop can then assume this and simply look for a best one.

To change the second loop so that it does the work of the first, something like this could be done:

  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

Note that to find e.g. the largest integer in a set of integers, you don't need the first pass since it is guaranteed that there will be an integer n such that there aren't any integers bigger than n in the list. Not true here; that there are elements in the list says nothing about whether there will be a solution (except that there might be). Note also that we have similar problems here with defining universally minimal values for comparisons... which, by establishing a baseline candidate, we avoid.


What if all values are larger than the threshold?

What's an appropriate initial value for v in the second cycle?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜