User123
User123

Reputation: 486

How to Do Sigma Sum Notation in Python?

How can I pass the expression as argument into the function and then execute it in Python?

def f(variable, function):
    # here calculate the function (unknown part)

f(3, 2 * variable)

The result should be 6. (f(x) = 2 * x; x = 3)

How can I do that?

Upvotes: 1

Views: 10201

Answers (1)

Cory Kramer
Cory Kramer

Reputation: 117886

def sigma_sum(start, end, expression):
    return sum(expression(i) for i in range(start, end + 1))

Note that to implement summation as it is done in mathematics, it is important to add one to the end of the range. Python stops before reaching the end value, whereas mathematics does not.

Example usage using a lambda function…

>>> sigma_sum(1, 10, lambda i: i**2)
385

…or using a named function…

def square(i):
    return i**2

>>> sigma_sum(1, 10, square)
385

Upvotes: 6

Related Questions