I am working on an educational project of Mathematics. An application that would make it possible to estimate the integrals by montecarlo’s method. however I would like the function to be integrated to be entered by the user. I am using the “text_input” but I would finally like this entry to be reconue in the definition of the “lambda” function but also to recognize some Numpy functions. Thank you for helping me.
This shows you how to create a function from a string:
userfun = """ def mynewfun(x): return x*x*x """ cc = compile(userfun , "newfun", "exec") exec(cc) mynewfun(5)
There you start from userfun which is a string, you compile it, you execute it !
Et voila! you can use your function.
You can proceed in that way for any text as long as you want.
It can contain any kind of Python statements, even classes.
If needed, you can also inccude a lambda.
You can of course assemble the string from what your user inputs and additional stuff that you may wish. For example, the string “xxx” would be provided by the user and you do the rest.
Note that this compile-exec is a bit unsecure since it can be exploited for code injection.
If the end user writes a code to crash the strealit server, it will succed.
Therefore, it would be good to restrict as much as possible what the end-user can enter.
Again something like “xxx” for example.
Maybe sympy could offer some advantages too.
thanks a lot, i used it and it’s running very well. I’m so proud of python
here is what i used
fct1="f=lambda x :" fct=st.sidebar.text_input("f(x)",value="x") fonction=fct1d+fct exec(fonction)
with this i was able to do any operations on that function
I will try these tricks