1

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?

User123
  • 476
  • 7
  • 22

1 Answers1

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

Example usage using a lambda function

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

or using a named function

def square(i):
    return i**2

>>> sigma_sum(1, 10, square)
285
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • You have missed something: You haven't included the last number (in that case it's 10). I have corrected. – User123 Feb 18 '20 at 18:21
  • I deliberately did not include the last value, which is canonical for Python and referred to as [half-open](https://stackoverflow.com/questions/11364533/why-are-slice-and-range-upper-bound-exclusive) range. Many slicing and indexing operations in Python work in this way. For example look at `print(list(range(1,10)))` – Cory Kramer Feb 18 '20 at 19:00
  • 1
    I have asked this for the mathematical sum, on the general way. In mathematics, we always include the last variable, if you want this or no. So please correct it. – User123 Feb 18 '20 at 19:05