Is there a way to plot a "function string" in python? [closed] - python

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 months ago.
Improve this question
Example: The user types "(x^2 + 5)^3" into the terminal and the script plots the function like WolframAlpha would do.
Is there an easy way to do that in python?
The function might include abs(), sqrt() etc.
Thanks in advance for your responses

You could try using eval with an inputted X or default x:
import matplotlib.pyplot as plt
import numpy as np
import re
def get_variables(input_string):
count = 0
matches = re.findall(r'(?i)[a-z]', input_string)
return set(matches) #returns unique variables
function = input('Input Function: ')
variables = get_variables(function)
print(variables, type(variables), function)
varDict = {v: np.arange(100) for v in variables} #maps the variable names to some default range
for v in variables: #changes the function string to work with the newly defined variables
pattern = r'\b%s\b' %v
function = re.sub(pattern,r'varDict["%s"]' %v,function)
answer = eval(function) #evaluates the function
if len(variables) == 1:
plt.plot(*varDict.values(),answer) #plot the results, in this case two dimensional
else:
ax = plt.axes(projection="3d")
ax.plot3D(*varDict.values(),answer) # line
#ax.scatter3D(*varDict.values(),answer); #scatter
plt.show()
You can change the 3d settings if you want a scatterplot or add logic to make a shape (ie using meshgrid)
Just be sure that the eval statements are fully sanitized. This also requires the function to be inputted in python syntax (** not ^), unless you want to add functions to edit common syntax differences in the string.

Related

Convert variable contents to string in python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last month.
This post was edited and submitted for review last month and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
I have a variable which has an equation .I'm trying convert the equation that the varibale has into a string and compute the results
Eg
def func1(x):
y = x + 5
return y, 'x+5'
x as input can vary since I'm iterating
through multiple values
Say
h[0][1] = 5
func1(h[0][1])
Output - 10, "h[0][1]+5"
Required result
I need x+5 as string and the computed result of y as a while calling func1
Eval and exec seemed like a probable solution but they perform the inverse of what is needed
I'm not sure I understand why you'd want this but given that the variable holding the equation would be known when coding, you could just wrap the equation in a function. Eg:
def add_five(x):
return (x + 5, "x + 5")
x = 10
y = add_five(x)
print("Answer is", y[0])
print("Equation is", y[1])

Python index error when trying to make a mean [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm trying to make an average but for some reason when I try to make one it doesn't work.
I have global variables and array defined at the begining of my document :
vent_moyenne_km = []
compteur_moyenne=0
I have one of my function that is called every X time. In that one, I calculate a velocity with some value that are display on a label of my interface. that part is working, but not the mean
global compteur_moyenne
compteur_moyenne += 1
ventkmh = (vent_1[3][0]*256 + vent_1[4][0]) /100 *3.6
label_vent2_2.config(text= "%.2f" % ventkmh)
vent_moyenne_km.append("%.2f" % ventkmh)
vent_1.clear()
if compteur_moyenne == 5:
compteur_moyenne = 0
print(vent_moyenne_km)
label_vent4_2.config(text=statistics.mean(vent_moyenne_km))
vent_moyenne_km.clear()
of course in my imports I have :
import statistics
When I comment the line label_vent4_2.config(text=statistics.mean(vent_moyenne_km)), everything works and I see in the terminal my array with 5 values. I also tried numpy and even tried to make a for items in array: then add then manually, and everytime I get the error : class 'IndexError'
I'm really not sure how to fix that.
For calculating an average of a list just use numpy:
def function():
value = random.randint(0,1)
return value
list = []
for i in range(100):
list.append(function())
if i%5 == 0:
print(np.average(list))

Access the same attribute from different objects in Python [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Suppose I have a class called Cube and I create three objects:
class Cube():
def __init__(self, volume):
self.volume = volume
a = Cube(param_a)
b = Cube(param_b)
c = Cube(param_c)
I was wondering if I can write a function, to which the user can give a format, and the function can apply the format to the objects? For example:
>>> print_all(dummy_cube.volume)
a.volume
b.volume
c.volume
So basically the function contains a loop which will replace dummy_cube to a, b, c.
I know I can use something like getattr(), but it has limits. For example, I hope that the function can print whatever format the user gives:
>>> print_all( (dummy_cube.volume)**2 + 1 )
(a.volume)**2 + 1
(b.volume)**2 + 1
(c.volume)**2 + 1
Is there any good way to do this?
Edit: As the comments pointed out, yes the function can take a list, and I intend it to return the numerical values instead of the format itself.
With a list I can do like:
cube_list = [a, b, c]
for cube in cube_list:
print( (cube.volume)**2 + 1 )
But I am still not sure how I can do it with arbitrary expressions given by the user.
The user can supply a function.
def print_all(f):
for cube in cube_list:
print(f(cube))
import operator
print_all(operator.attrgetter('volume'))
print_all(lambda c: c.volume**2 + 1)

Python: Derivative of trig functions [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I am trying to identify what the problem with the differentiation of trig functions in Python. I use scipy.misc.derivative.
Correct case:
def f(x):
return math.sin(x)
y=derivative(f,5.0,dx=1e-9)
print(y)
This will give a math.cos(5) right?
My problem is here. Since python accepts radians, we need to correct what is inside the sin function. I use math.radians.
If I code it again:
def f(x):
return math.sin(math.radians(x))
y=derivative(f,5.0,dx=1e-9)
print(y)
This will give an answer not equal to what I intended which should be math.cos(math.radians(5)).
Am i missing something?
You have to be consistent with the argument of the trigonometric function. Is not that "Python accepts radians", all programming languages I know use radians by default (including Python).
If you want to get the derivative of 5 degrees, yes, first convert to radians and then use it as the argument of the trigonometric function. Obviously, when you do
y=derivative(f,5.0,dx=1e-9)
using
def f(x):
return math.sin(x)
you get f'(x)=cos(x) evaluated at 5 (radians). If you want to check that the result is correct this is the function to check, not f'(x)=cos(math.radians(x)), which will give you another result.
If you want to pass 5 degrees, yes, you will need to get the radians first:
y=derivative(f,math.radians(5.0),dx=1e-9)
which will be the same as cos(math.radians(5)).
Here is a working example
from scipy.misc import derivative
import math
def f(x):
return math.sin(x)
def dfdx(x):
return math.cos(x)
y1 = derivative(f,5.0,dx=1e-9)
y2 = dfdx(5)
print(y1) # 0.28366
print(y2) # 0.28366

Is this a good way to get the average of the input numbers? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I'm writing a function to return the mean of the user's comma-separated input.
def get_average () :
grades = input()
grades = grades.split(",")
grades = [int(x) for x in grades]
average = (sum(grades))/(len(grades))
return round(average, 2)
Is this a good way to do so? What about the fact that I redefined the grades variable twice? Is there a more practical way to do it?
Reusing grades just makes the program harder to read, as grades now means three different, semantically incompatible things. Try using more descriptive names, then combining intermediate steps. For instance:
input_line = input("Please enter the grades, separated by commas")
grades = [int(x) for x in input_line.split(',')]
Other than the superfluous outer parentheses in the mean computation, you're doing fine so far.
You could write it a bit more elegant, but nothing is wrong with redefining grades in these three consecutive lines. It works, and as it is so close together it won't create confusion.
Here would be my go for a more elegant solution using python's statistics module from the standard lib:
import statistics
def get_average():
user_input = input('Please enter integer numbers separated by commas: ')
average = statistics.mean(map(int, user_input.split(',')))
return round(average, 2)
This is fine, to be more pythonic you can chain calls like:
grades = [int(x) for x in grades.split(',')]
without having to use a temporary assignment of .split()
You can do the same with the round() call:
return round(sum(grades) / len(grades), 2)

Categories