Passing a parameter to filter

T

Thomas Philips

To experiment with filtering, I define a function f(x,k) as follows return x%k==0

I can check that it works by typingFalse

Now, I try to filter a range using
Traceback (most recent call last):
File "<pyshell#16>", line 1, in -toplevel-
filter(f(k=3),range(20))
TypeError: f() takes at least 1 non-keyword argument (0 given)

I next try
Traceback (most recent call last):
File "<pyshell#17>", line 1, in -toplevel-
filter(f(3),range(20))
TypeError: 'bool' object is not callable

But, as k defaults to 2, I get exactly what I expect from
filter(f,range(20)) [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

What's wrong with my syntax when passing the parameter k=3?

Sincerely

Thomas Philips
 
F

Fredrik Lundh

Thomas said:
Now, I try to filter a range using

f(k=3) calls the function, so you're passing the return value to filter,
not the function itself. that's obviously not what you want.

some alternatives:

filter(lambda x: f(x, 3), range(20))

[x for x in range(20) if f(x, 3)]

the lambda form creates an "anonymous function" that takes one
argument, and calls your f() function with the right arguments.

the second form is a "list comprehesion", which is a compact way
to write for-in loops.

</F>

(this reply will be followed by 20 replies pointing you to 150-line scripts
that lets you do what you want by a combination of metaclasses, byte-
code rewriting, and iterators...)
 
T

Thomas Heller

Fredrik Lundh said:
filter(lambda x: f(x, 3), range(20))

[x for x in range(20) if f(x, 3)]
</F>

(this reply will be followed by 20 replies pointing you to 150-line scripts
that lets you do what you want by a combination of metaclasses, byte-
code rewriting, and iterators...)

In your list you forgot the additional 20 replies talking about currying
(and the replies to them that currying is something different)

Thomas
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,012
Latest member
RoxanneDzm

Latest Threads

Top