[Tutor] min() & mutable sequences

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Fri, 21 Dec 2001 12:24:42 -0800 (PST)


On Fri, 21 Dec 2001, dman wrote:

> On Thu, Dec 20, 2001 at 01:43:27PM +0800, Andy W wrote:
> | closest=min([robot.distance for robot in robots])
> | 
> | Okay, I now have the closest *distance*.
> | Say more than one instance has the same distance, will min() return the
> | first instance with that smallest distance? Because if that is so, I could
> | then just get the related instance using:-
> 
> No.  min() returns the smallest object in the list.  In this case the
> object is a number, not a robot.
> 
> | closest_index=[robot.distance for robot in robots].index(closest)
> | #Yeah, I used that list comprehension twice, this is just for demonstration,
> | though.
> | closest_robot=robots[closest_index]
> 
> 
> I'm kinda surprised that min() doesn't take a comparison function like
> sort does.


Here's an example of writing our own mymin() function that does take a
comparision function:

###
def mymin(elements, cmp_func=cmp):
    if len(elements) == 0:
        raise ValueError, 'mymin() of empty sequence'
    current_min = elements[0]
    for e in elements[1:]:
        if cmp_func(e, current_min) < 0:
            current_min = e
    return current_min
###


This mymin() is useful because now we can tell it what it means for one
thing to be 'smaller' than another.  Take a look:

###
>>> def cmpByLength(x, y): return cmp(len(x), len(y))
>>> mymin(['i', 'am', 'the', 'wind'])
'am'
>>> mymin(['i', 'am', 'the', 'wind'], cmpByLength)
'i'
###

Happy holidays!