TurtleDave
TurtleDave

Reputation: 55

How i do i change this code so it can deal with functions

The function below takes 3 parameters (f, a, and b). Here f is a function and a and b are lower and upper bounds respectively, and f is the function to be summed over. #to calculate the sum of f from a to b

def sum(f, a, b):
 total = 0
 for i in range(a, b+1):
 total += f(i)
 return total

Question 1. Type in the above code and calculate the sum of integers from 1 to 10, and 1 to 100 and 1 to 1000

Upvotes: 0

Views: 64

Answers (3)

Rudziankoŭ
Rudziankoŭ

Reputation: 11251

Or use a functional style and you will come to success:

def product(f, a, b):
    return reduce(lambda x, y: x*y, [f(n) for n in range(a, b+1)])

Run it going with function eg spam:

def spam(x):
    return x

print(product(spam, 1, 3))

>>>6

Edited:

W/o f param it will looks:

def product(a, b):
    return reduce(lambda x, y: x*y, [n for n in range(a, b+1)])
print(product(1, 5))

Upvotes: 0

zondo
zondo

Reputation: 20336

Just as adding 0 does nothing, multiplying by 1 does nothing. Therefore, just use that as the start:

def product(f, a, b):
    total = 1
    for i in range(a, b+1):
        total *= f(i)
    return total

Upvotes: 0

Cory Kramer
Cory Kramer

Reputation: 117876

Similar idea, but use *= instead of +=

def product(f, a, b):
    total = 1
    for i in range(a, b+1):
        total *= f(i)
    return total

For example

def foo(x):
    return x

>>> product(foo, 1, 5)
120

Upvotes: 1

Related Questions