# help with silly algorhythm

Gerson Kurz gerson.kurz at t-online.de
Fri Feb 15 13:46:03 EST 2002

```On Fri, 15 Feb 2002 11:24:24 -0800, Jeff Shannon <jeff at ccvcorp.com>
wrote:

>>
>> > * list of input values =[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
>> > * a list of acceptable new 'partner values' = [1, 3, 7, 10]
>>
>> input_list = range(12)
>> partner_values = [1,3,7,10]
>>
>> > so we might get (in mode 1: all closest higher value)
>> > [ [0, 1], [1, 3], [2, 3], [3, 7], [4, 7], [5, 7], [6, 7], [7, 11]....
>>
>> GetUpper = lambda i,p:filter(lambda x:x[1],[(y,(filter(lambda
>> x:x>y,p)+[None])[0]) for y in i])
>>
>> In typical Python fashion the code is obvious.
>
>Heh.  I positively cannot make heads or tails of that lambda--perhaps its a
>shortcoming of mine, but extended lambdas like that make my eyes glaze and my
>brain shut off....

OK, my post was meant as a joke. Besides, it became clear to my that I
assumed the lists were ordered in advance. Here is, in explicit
notation, what the above lambda expression does, and how.

def GetUpper(i,p):
result = []

# this is the [for y in i] array
for y in i:

# this is the innermost lambda
def IsGreaterThanY(x):
return x>y

# will return a list, where each
# element is greater than the current y
temp = filter( IsGreaterThanY, p )

# make sure the list has at least one element
# (namely "None")
temp = temp + [None]

# return the lowest of that list = the
# lowest element that is higher than y
temp = temp[0]

# this is done by the filter x[1]: it will
# remove all elements, where x[1] is None
if temp:
result.append( (y, temp) )

return result

GetLower() looks similar, but for two changes:

- IsGreaterThanY is replaced by IsLowerThanY, with obvious
implementation
- the last element of the temp list is choosen (=the highest element
that is lower than y)