0

I imported myList from a .txt file (I converted the numbers to integers)

from math import *
myList = [100, 'sin', 0, 1]
x = pi

How would I go about calling the sin function for my given value of x?

myList[1](pi)

I hoped this would simply return sin(pi), but it does not, because it is just the string 'sin(x)'

  • 2
    We're in `eval` land here, the question is *why* do you want to do this? – timgeb Mar 29 '17 at 17:12
  • What are you reasons for doing this? There is probably a better solution to your original problem. – Code-Apprentice Mar 29 '17 at 17:13
  • [SymPy](http://www.sympy.org/en/index.html) has some tools that could help. – user2357112 Mar 29 '17 at 17:13
  • Define x first. Then define myList, but take out the quotation marks. – zondo Mar 29 '17 at 17:15
  • I want to make a function that will perform Riemann Integral with a finite number of intervals in a partition. The idea is that I will find a approximation to integral of sin(x) between x=0 and x=1. I will have 100 intervals in my partition. – Jack Malrock Mar 29 '17 at 17:15
  • One way to use sympy is described in http://docs.sympy.org/dev/tutorial/basic_operations.html#converting-strings-to-sympy-expressions – Lutz Lehmann Mar 29 '17 at 17:23
  • How would I go about removing the quotation marks in 'sin' – Jack Malrock Mar 29 '17 at 17:46
  • There are no quotation marks in that string, they are only added in the input or printed output to signal an object of type string. Thus you can not remove them. – Lutz Lehmann Mar 29 '17 at 19:01

1 Answers1

1

Do not store functions as string literals, store the actual functions.

>>> from math import sin, exp, log
>>> funcs = [sin, exp, log]
>>> x = 0
>>> funcs[0](x)
0.0
>>> funcs[1](x)
1.0
>>> funcs[2](2.71)
0.9969486348916096

However, if you don't plan to do something more involved with that list of functions, you can just call them directly.

timgeb
  • 76,762
  • 20
  • 123
  • 145
  • Thanks for your response. I read the list from a text file, is there a way to read it such that the actual functions are put into the list? The text file I made to be of this format: 100 sin(x) 0 1 – Jack Malrock Mar 29 '17 at 17:20
  • 1
    @JackMalrock I'd circumvent this entirely by having the textfile be a Python module from which you can import a list of functions, i.e. `from mathtools import funclist`. If you don't want to do this, maybe SymPy. – timgeb Mar 29 '17 at 17:22