Can you pass functions as arguments?

Bengt Richter bokr at oz.net
Mon Dec 19 07:50:11 EST 2005


On 18 Dec 2005 23:18:48 -0800, Paul Rubin <http://phr.cx@NOSPAM.invalid> wrote:

>bobueland at yahoo.com writes:
>> I want to calculate f(0) + f(1) + ...+ f(100) over some function f
>> which I can change. So I would like to create a function taking f as
>> argument giving back the sum. How do you do that in Python?
>
>You can just pass f as an argument.  The following is not the most
>concise or general way, it just shows how you can pass a function.
>
>    def square(x): 
>       return x**2
>
>    def sum100(f):    # f(0)+f(1)+...+f(100)
>       s = 0
>       for i in xrange(101):
>          s += f(i)
>       return s
>
>    print sum100(square)    # pass square as an argument

or
 >>> def square(x): return x*x
 ...
 >>> from itertools import imap
 >>> sum(imap(square, xrange(101)))
 338350

which seems to agree with
 >>> def sum100(f):
 ...     s = 0
 ...     for i in xrange(101):
 ...        s += f(i)
 ...     return s
 ...
 >>> sum100(square)
 338350

or if the OP actually wants the specific function,
 >>> def sum100a(f): return sum(imap(f, xrange(101)))
 ...
 >>> sum100a(square)
 338350

Regards,
Bengt Richter



More information about the Python-list mailing list