Can you pass functions as arguments?

B

bobueland

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?
 
P

Paul Rubin

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
 
X

Xavier Morel

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?
Python functions (and classes, and modules) are first-class objects, so
you can use them as regular objects: send them as arguments, generate
and return them from functions, ...

BTW, if your goal is to create that kind of sums of function results, I
think you'd be interested in using both Python's _generators_ and the
built-in function *sum*.
 
B

Bengt Richter

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
338350

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

or if the OP actually wants the specific function, 338350

Regards,
Bengt Richter
 
P

Paul Rubin

or if the OP actually wants the specific function,
338350

Similarly with generator comprehension, if I have the syntax right:

def sum100c(f): return sum(f(i) for i in xrange(101))
 

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
474,274
Messages
2,571,366
Members
48,055
Latest member
RacheleCar

Latest Threads

Top