fp/lambda question

Fernando Pérez fperez528 at yahoo.com
Mon Apr 15 13:57:34 EDT 2002


Duncan Booth wrote:

>>> def relatively_prime(a, b): return gcd(a, b) == 1
>> 
>> Thats funny, I wanted to do that but I don't know how to use filter
>> with a function that takes 2 variables. E.g., to get a list if all
>> numbers less than 10 relatively prime to 3, I would write
>> 
>>      filter(relatively_prime, range(1, 10)) # aaah, where does the 3
>>      go???
>> 
> If you want this readable then use a list comprehension:
>    [ n for n in range(1,10) if relatively_prime(n, 3) ]
> 

And if you insist on a lambda solution, it's not that bad (but at least to me, 
less readable than the list comprehension):

filter(lambda n:relatively_prime(n,3),range(1,10))

cheers,

f



More information about the Python-list mailing list