Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Please help to justify the code redundancy

Tags:

python

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 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

Thanks!

like image 629
Andrey Lukyanov Avatar asked Jul 01 '26 03:07

Andrey Lukyanov


1 Answers

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.

like image 144
Patrick87 Avatar answered Jul 03 '26 17:07

Patrick87



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!