1
import matplotlib.pyplot as plt
string = input("Please enter a function: ")

Here the code that I want to convert. I want to convert this to variable to graph the function. Other part of the code will be:

domain = [x for x in range(-10,10)]
range = [string for x in domain]

And I want the string in range be variable in order to Python can run the code. For example if a user enter, let's say,

string = "x ** 2 + x * 2 + 1"

Then I want a method or something that will convert this string to a variable. And in the end I want to get:

string = x ** 2 + x * 2 + 1

By getting this I can get a plot from matplotlib. Finally code will be:

domain = [x for x in range(-10,10)]
range = [x ** 2 + x * 2 + 1 for x in domain]

Thanks in advance!

2
  • 1
    You may want to take a look at SymPy, which is a library for symbolic mathematics. Also, when you write range = ... you are overwriting the built-in range function so you should use a different variable name Commented Jul 15, 2021 at 9:26
  • Thanks a lot! It will work I have just looked at it! Commented Jul 15, 2021 at 9:31

1 Answer 1

1

A quick & dirty approach would be to use the native function eval. For instance define the following high-order function:

def str_to_func(string):
    return lambda x: eval(string)

which can be used in this way:

function = str_to_func(string)
values = [function(x) for x in domain]
plt.plot(domain, values)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! I will try this also!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.