where or filter on list

Larry Bates larry.bates at websafe.com
Sat Sep 2 00:03:00 CEST 2006


What I mean is: What if there are two items that are
equidistant to what you are searching for?


Example:

foo = [-5,-1,1,3,5]
print closest(0, foo)

-1 and 1 are both "equally close" to zero that I'm
searching for.  This is an edge case that you didn't
define an answer to and closest function that I
wrote may (or may not) return the correct answer.

-Larry

charles.hebert at gmail.com wrote:
> Thanks all !
> 
>> Question: what if two values are equidistant?
> 
>>>> def closest(foo,v):
> ...     intermed = [(abs(v), v) for v in foo]
> ...     intermed.sort()
> ...     return [x[1] for x in intermed if x[0] == intermed[0][0]]
> ...
>>>> print closest([-20,-10,10,15],0)
> [-10, 10]
> 
> Works fine !
> 
> (now with sorted ... ?)
> 



More information about the Python-list mailing list