where or filter on list
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?
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.
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 for x in intermed if x == intermed]
>>>> print closest([-20,-10,10,15],0)
> [-10, 10]
> Works fine !
> (now with sorted ... ?)
More information about the Python-list