0

I'm learning python and I'm not sure how to pass a string to lambda.

This is a basic example of Riemann sum:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import numpy as np
#f0 = str(input("ingrese funcion:"))
f = lambda x: x**2
sum = 0.0
a = float(input("ingrese límite inferior:"))
b = float(input("ingrese límite superior:"))
n = int(input("ingrese cantidad de subintervalos:"))
i = b-a #la longitud del intervalo
dx = i/n #que diferencia habrá cada vez que evalúes
for xi in np.arange(a,b,dx):
    sum += dx*f(xi)
print "Valor de la suma de Riemann de f en [a,b] = " + str(sum)

My idea was to let f0 as a user defined string (e.g. x**2 + 10) and then pass f0 to f. Of course doing that should return an "undefined" error.

2
  • 1
    Do you want the user to specify the function? Commented Sep 4, 2017 at 23:10
  • yes, in the comment below I did put what worked Commented Sep 4, 2017 at 23:53

1 Answer 1

1

The easiest way to do this is using eval:

f0 = "x**2"
f = eval("lambda x:" + f0)
print f(2) # 4

Note that this will accept and execute any python expression. This means that error checking can be difficult (because there are almost no constraints on the function the user can provide) and opens major security holes (because the user can cause your program to execute arbitrary code). This isn't a problem for quick demonstrations, but should be avoided in anything like a production system.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.