suppose I have a function:
def func(t):
a=5;b=-7;c=4;d=2
return a*t**3+b*t**2+c*t+d
beside returning the value of the function, I am also trying to get the function literally, as, when called, I will get:
a*t**3 +b*t**2+c*t +d = <actual mathematical value>
My final goal is to get it correct as a LaTeX expression to write the statement in matplotlib.
Any help?
UPDATE Dear all, Thanks for your reply. But I just don't want to write the function once again, as you have shown, is some way like:
return "a*t**3+b*t**2+c*t+d = " + str(a*t**3+b*t**2+c*t+d)
(I can easier do that in plt.txt directly, right?)
I just want to transform the function copied literally:
def func(t):
a=.05;b=-.07;c=.04;d=.02
return a*t**3+b*t**2+c*t+d
def strf():
# return(r"$a*t**3+b*t**2+c*t+d$")
return (str(func))
# expecting this to give the output
# r"$a*t**3+b*t**2+c*t+d$"
Is this what you mean?
def func(t):
a = 5
b = -7
c = 4
d = 2
return "a*t**3+b*t**2+c*t+d = " + str(a*t**3+b*t**2+c*t+d)
def func(t):
a = 5
b = -7
c = 4
d = 2
exp = "a*t**3+b*t**2+c*t+d"
return f"{exp} = {eval(exp)}"
I think this is it
You can use the f-string:
def func(t):
a = 5
b = -7
c = 4
d = 2
result = a * t**3 + b * t**2 + c * t + d
return result, f'a * t**3 + b * t**2 + c * t + d = {result}'
res, str_ = func(5)
print(res)
print(str_)
Output:
472
a * t**3 + b * t**2 + c * t + d = 472
I don‘t recommend you to use the function eval() as in another solutions.
Related
I need to make a calculator with a few simple operations but only using the successor function in Python
with sum, multiplication and exponential but I am having some logic problems to implement the code, can you help me?
this is what i got right now:
def suc(a):
return a + 1
def sum(a,b):
c = 0
for i in range(b):
c = suc(c)
return c
def multiplication(a,b):
c = 0
for i in range(b):
c = sum(c,c)
return c
def exp(a,b):
c = 0
for i in range(b):
c = multiplication(c,c)
return c
To make your code work you need to change it to
def suc(a):
return a + 1
def sum(a, b)
for i in range(b):
a = suc(a)
return a
def multiplication(a,b):
c = 0
for i in range(b):
c = sum(c, a)
return c
def exp(a,b):
c = a
for i in range(b-1):
c = multiplication(c,a)
return c
Here is the list of problems in the code sample:
sum function is not adding the 2 operands
multiplication function is not adding the left operand to itself
exp function did not initialize the temp value to 1
Here is the working code with the above problems resolved:
# File name: calculator-demo.py
def suc(a):
return a + 1
def sum(a, b):
for i in range(b):
a = suc(a)
return a
def multiplication(a, b):
c = 0
for i in range(b):
c = (c + a)
return c
def exp(a, b):
c = 1
for i in range(b):
c = multiplication(a, c)
return c
print("sum(2, 3) = ", sum(2, 3))
print("multiplication(2, 3) = ", multiplication(2, 3))
print("exp(2, 3) = ", exp(2, 3))
Output:
> python calculator-demo.py
sum(2, 3) = 5
multiplication(2, 3) = 6
exp(2, 3) = 8
Using python 3: I have three functions: montePi, isInCircle and main.
I need to have the isInCircle called by montePi. The function will work, it just says that isInCircle is not defined. How can I define it?
import random
import math
def montePi(numDarts):
inCircle = 0
def isInCircle(x, y, r):
r = 1
d = math.sqrt(x**2 + y**2)
if d <= r:
return True
else:
return False
for i in range(numDarts):
x = random.random()
y = random.random()
d = math.sqrt(x**2 + y**2)
if d <= 1:
inCircle = inCircle +1
pi = inCircle / numDarts * 4
return pi
def main():
print(montePi(100))
print(montePi(1000))
print(montePi(10000))
print(montePi(100000))
main()
Because function isInCircle is defined in montePi, it can be called within montePi but not other functions as it is local. If you define isInCircle outside of montePi then you'll be able to call it from main.
Not sure what you're trying to program here, but there seems to be a chance that this question, regarding functions within functions can help you decide what you want here. Here is a question that covers how scopes work.
Should you need to call isInCircle from main or outside main, then this is how it should be formatted;
import random
import math
def isInCircle(x, y, r):
r = 1
d = math.sqrt(x**2 + y**2)
if d <= r:
return True
else:
return False
def montePi(numDarts):
inCircle = 0
for i in range(numDarts):
x = random.random()
y = random.random()
d = math.sqrt(x**2 + y**2)
if d <= 1:
inCircle = inCircle +1
pi = inCircle / numDarts * 4
return pi
def main():
print(montePi(100))
print(montePi(1000))
print(montePi(10000))
print(montePi(100000))
main()
Let's say that I am trying to build a model object m.
I would like to attach some variables and equations to m, so I have:
class ModelBuilder():
def build_model():
m = MyModel()
self.add_variables(m)
self.add_equations(m)
if self.feeling_good:
self.add_other_equations_sometimes(m)
return m
def add_variables(self, m):
m.a = MyVar(domain=Reals)
m.b = MyVar()
m.c = MyVar()
...
def add_equations(self, m):
m.pythagoras = MyEqn(expression=m.a ** 2 + m.b ** 2 == m.c ** 2)
...
def add_other_equations_sometimes(self, m):
m.eqnname = MyEqn(expression=m.a + m.b == m.c)
...
This works. But let's say that I have quite a few variables and some complicated equations where I would rather not have to write m.<name> for everything in the expressions. I would rather have a ** 2 + b ** 2 == c ** 2 to look at.
I can do this if I put everything in one function and have:
def add_modelthings(self, m):
a = m.a = MyVar(domain=Reals)
b = m.b = MyVar()
c = m.c = MyVar()
...
m.pythagoras = MyEqn(expression=a ** 2 + b ** 2 == c ** 2)
...
if self.feeling_good:
m.eqnname = MyEqn(expression=a + b == c)
...
But then I have a really cluttered function for a large model. It is tempting to use locals() or globals():
class ModelBuilder():
def build_model():
m = MyModel()
var_dict = self.add_variables(m)
self.add_equations(m, var_dict)
if self.feeling_good:
self.add_other_equations_sometimes(m, var_dict)
return m
def add_variables(self, m):
a = m.a = MyVar(domain=Reals)
b = m.b = MyVar()
c = m.c = MyVar()
...
return locals()
def add_equations(self, m, var_dict):
locals().update(var_dict)
m.pythagoras = MyEqn(expression=a ** 2 + b ** 2 == c ** 2)
...
def add_other_equations_sometimes(self, m, var_dict):
locals().update(var_dict)
m.eqnname = MyEqn(expression=a + b == c)
...
But after reading all the warnings about updating locals() and being wary that globals() updates variable values across the whole module and not just the class, I am not sure what the best way is to accomplish this simplicity in the variables for my mathematical expressions.
The code which I wanna improved now looks something like below,
which f0 and f1(or more than 2 function) need the same variables.
I have to code about 50 lines to describe the variable setting at each function.
how can I do this more pythontic?
--f0.py
import csv
def gen(csv_f):
# var define
for row in csv.DictReader(open(csv_f)):
c += row['x']
...
a = 1
b = 2
...
# do sth in f0
xx = a + b
...
str = ...
return str
--f1.py
import csv
def gen(csv_f):
# var define
for row in csv.DictReader(open(csv_f)):
c += row['x']
...
a = 1
b = 2
...
# do sth in f1
xx = a*b + b
...
str = ...
return str
--genstr.py
from f0 import *
from f1 import *
f = open('xxx.x','w')
f.write(f0.gen(1)+f1.gen(1))
f.close()
(I don't really know how to use class, but I found this could help my problem
just describe maybe it will help understanding my question )
I try to do it with class, so i can access by inherit conf.
I know I can access by 'self.a', but is there any way I can direct use 'a' in the function?
--conf.py
class conf:
def __init__(self, csv_f):
# var define
for row in csv.DictReader(open(csv_f)):
c += row['x']
...
self.a = 1
self.b = 2
...
--f0.py
import conf
class f0(conf):
def __init__(self):
config.__init__(self, csv_f) #this line is not correct
def gen():
# var set
c = self.c
a = self.a
b = self.b
# do sth in f0
xx = a + b
...
str = ...
return str
--f1.py
import conf
class f1(conf):
def __init__(self):
config.__init__(self, csv_f) #this line is not correct
def gen():
# var set
c = self.c
a = self.a
b = self.b
# do sth in f1
xx = a + b
...
str = ...
return str
--genstr.py
from f0 import *
from f1 import *
f = open('xxx.x','w')
f.write(f0.gen(1)+f1.gen(1))
f.close()
The code is slightly confusing and i'm not sure what exactly you are trying, but here are some general help.
This code:
for row in csv.DictReader(open(csv_f)):
c += row['x']
Will append the content of coloumn x to c.
import conf
class f0(conf):
def __init__(self, csv_f):
super(f0,self).__init__(self) # Fixed
self.csv_f = csv_f
def gen(self):
# var set
c = self.c #
a = self.a
b = self.b
# do sth in f0
xx = a + b
Instead of c = self.c you can use self.c where ever you need c.
from f0 import *
from f1 import *
f = open('xxx.x','w')
f.write(f0(filename).gen()+f1(filename).gen())
f.close()
Your first two functions differ in these lines:
xx = a + b
vs.
xx = a*b + b
You can pass in this as as additional argument.
def gen(csv_f, f):
# var define
for row in csv.DictReader(open(csv_f)):
c += row['x']
...
a = 1
b = 2
...
# use the passed function
xx = f(a, b)
...
return str
l0 = lambda a, b: a + b
l1 = lambda a, b: a * b + b
# call gen with one of these lambdas as the second argument
gen(1, l0)
gen(1, l1)
I'd like to see the values of t when the values of AlfaSegundo, AlfaMinuto and AlfaHora are the same.
def PosicaodoponteiroSegundo(t):
AlfaSegundo = 6 * t % 360
return AlfaSegundo
def PosicaodoponteiroMinuto(t):
AlfaMinuto = t / 10 % 360
return AlfaMinuto
def PosicaodoponteiroHora(t):
AlfaHora = t / 120 % 360
return AlfaHora
a = PosicaodoponteiroSegundo(t)
b = PosicaodoponteiroMinuto(t)
c = PosicaodoponteiroHora(t)
def Instantes(a, b, c):
a = b
b = c
return t
print Instantes(a, b, c)
What should I do?
Thanks.
I do not think this does what you think it does
def Instantes(a, b, c):
a = b
b = c
return t
print Instantes(a, b, c)
Within the function, a, b, and c all refer to the values that you passed in. Effectively you could replace print Instantes(a, b, c) with print t
All you have to do here is say:
if a == b == c:
print t
EDIT:
Because you are using the mod, you can never reverse the function. What you can do instead is write a function that takes t and passes it to your other functions.
def some_function(t):
segundo = PosicaodoponteiroSegundo(t)
minuto = PosicaodoponteiroMinuto(t)
hora = PosicaodoponteiroHora(t)
if segundo == minuto == hora:
print(t)
a = PosicaodoponteiroSegundo(t) = (6 * t) % 360
b = PosicaodoponteiroMinuto = (t / 10) % 360
c = PosicaodoponteiroHora = (t / 120) % 360
for now you can probably ignore the modulo's
a = 6*t
b = t/10
c = t/120
this leads to solve for t S.T.
t = a/6.0
t = b*10
t = c*120
unfortunately this does ignore the modulo 360 which is likely unrecoverable as well as the truncation of your division so t=a/6.0 is likely your best bet