Re: Want to Use filter() with multi-variable function

Guido.van.Rossum@cwi.nl
Wed, 27 Jul 1994 18:42:43 +0200

> I have a list of numbers; I want a quick and efficient way to
> find the subset of these numbers which lie between two limits.
> However these numbers are determined within the program itself.
>
> I wanted to do something like
>
> def checklims(a,b,c) :
> if a >= b and a < c :
> return 1
> else :
> return 0
>
> ...
>
> newlist = filter(checklims,oldlist)
>
>
> The problem is (as far as I can tell) that filter expects to get
> a one-parameter function, and supplies each element of that list
> as a parameter, one by one. So how do I tell "checklims" which
> limits to use??

One solution would be to use default arguments. E.g.

lowerbound = compute_lowerbound()
upperbound = compute_upperbound()

def inrange(x, l=lowerbound, u=upperbound):
return l <= x < u

newlist = filter(inrange, oldlist)

More complicated in this simple case, but of more educational value
because it's usable in other situations too, is to use a class:

def RangeChecker:
def __init__(self, lowerbound, upperbound):
self.lowerbound = lowerbound
self.upperbound = upperbound
def check(self, x):
return self.lowerbound <= x < self.upperbound

lowerbound = compute_lowerbound()
upperbound = compute_upperbound()

inrange = RangeChecker(lowerbound, upperbound)

newlist = filter(inrange, oldlist)

> I can't wait to see the Tim Peters solution on this one (where IS that
> guy anyway??)

He lost his job at KSR in a mass layoff. He might be back sometime
after the summer?

Personally, I'd like to see Steve Majewski win the Obfuscated Python
Contest with a solution for this question...

--Guido van Rossum, CWI, Amsterdam <Guido.van.Rossum@cwi.nl>
<URL:http://www.cwi.nl/cwi/people/Guido.van.Rossum.html>