How to write two variables in one line? [duplicate] - python

This question already has answers here:
How can I print multiple things (fixed text and/or variable values) on the same line, all at once?
(13 answers)
How to write multiple strings in one line?
(12 answers)
Closed 5 years ago.
I would like to write two variable in a file. I mean this is my code :
file.write("a = %g\n" %(params[0]))
file.write("b = %g\n" %(params[1]))
and what I want to write in my file is :
f(x) = ax + b
where a is params[0] and b is params[1] but I don't know how to do this ?
Thank you for your help !

If all you want to write to your file is f(x) = ax + b where a and b are params[0] and params[1], respectively, just do this:
file.write('f(x) = %gx + %g\n' % (params[0], params[1]))
'f(x) = %gx + %g' % (params[0], params[1]) is simply string formatting, where you're putting a and b in their correct spaces.
Edit: If you're using Python 3.6, you can use f-strings:
a, b = params[0], params[1]
file.write(f'f(x) = {a}x + {b}\n')

"f(x) = {a}x + {b}".format(a=params[0], b=params[1])
Is a clean solution

sorry I don't know Python, but I guess this
f = open('file', 'w')
x = 0;
a = 0;
b = 0;
result = a*x+b
a = str(a)
b = str(b)
x = str(x)
result = str(result)
f.write("f("+x+")="+result) #this is if you want result to be shown
print("f("+x+")="+result)
#or
f.write("f("+x+")="+a+""+x+"+"+b) #this is if you want actually show f(x)= ax+b
print("f("+x+")="+a+""+x+"+"+b)
again I don't know Python, but this is what I come up with by using : https://repl.it/HARP/1
I hope this helps

You target is to achieve is to write the equation below to be written inside the file.
f(x) = ax + b where a is params[0] and b is params[1]
What you should do is
file.write('f(x) = %gx + %g' % (param[0], param[1]))
which will write
"f(x) = 2x + 3" # if params[0] and params[1] are 2 and 3 resp
What you are doing is
file.write("a = %g\n" %(params[0]))
file.write("b = %g\n" %(params[1]))
This will write in the file as:
a = 2
b = 3
if params[0] and params[1] are 2 and 3 respectively

Related

For loop not working stating the endpoint is a float

So for context, I'm working on a program that requires the Guass formula. It's used to find for example, 5 + 4 + 3 + 2 + 1, or, 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1.
The formula is (n*(n + 1))/2,
I tried to incorporate this into a for loop, but I'm getting an error stating:
"'float' object cannot be interpreted as an integer"
This is my code:
# Defining Variables #
print("Give me a start")
x = int(input())
print("Give me a delta")
y = int(input())
print("Give me an amount of rows")
z = int(input())
archive_list = []
f = z + 1
stop = z*f
final_stop = stop/2
# Main Logic #
for loop in range(1,final_stop,1):
print("hi")
I would appreciate a response on why it wasn't working as well as a fixed code.
Thanks in advance!
As #ForceBru noted in his excellent comment, the problem is that the endpoint final_stop is a float, instead of an int.
The reason is because when computing it you used a single / instead of double.
If you replace
final_stop = stop/2
with
final_stop = stop//2,
then it should work fine.

Optimized summing beween ints and strs [duplicate]

This question already has answers here:
How do I put a variable’s value inside a string (interpolate it into the string)?
(9 answers)
Closed 2 years ago.
print("ax^2 + bx + c = d what is your values for them? ")
a = int(input(">a = "))
b = int(input(">b = "))
c = int(input(">c = "))
d = int(input(">d = "))
given_parabola = str(a) + "x^2 + " + str(b) + "x + " + (str(c)) + " = " + str(d)
Is there any other way that I can merge integer variables with strings?
The "best" approach really depends on what you're trying to do.
1. Concatenating lists with variable number of items (numbers and strings)
If you simply want to form a string from numbers and strings, I would first create a generator with generator expression and then join the strings with the join() method.
In [1]: a = [2, 'a', 3, 'x', 'foo', 8, 55]
In [2]: g = (str(x) for x in a)
In [3]: ' '.join(g)
Out[3]: '2 a 3 x foo 8 55'
Pluses
Can be used to concatenate any amount of strings and numbers, which can be in any order
Minuses
Probably not the most speed optimized, if you know more about the variables you are going to concatenate
2. Literal String interpolation
If you know what amount of numeric variables you want to concatenate with what strings, the problem is called string interpolation.
In Python 3.6+ you can use so-called f-strings to form string using a string template and a fixed number of variables. For example:
In [1]: a, b, c, d = 3, 2, 1, 5
In [2]: f"{a}x^2 + {b}x + {c} = {d}"
Out[2]: '3x^2 + 2x + 1 = 5'
Pluses
Probably the most speed optimized way to create a string from a template.
Minuses
This is not a general approach to "sum"/concatenate any amount of strings and numbers.
3. Using sympy for expression generation
Since your problem looks like being very specific: You want to create string from mathematical formula, you might want to look at sympy.
Installation
pip install sympy
Simple example
In [1]: from sympy import symbols, Eq, mathematica_code
In [2]: x, a, b, c, d = symbols('x a b c d')
In [3]: expr = Eq(a*(x**2) + b*x + c, d)
In [4]: var_dict = dict(a=3, b=2, c=1, d=5)
In [5]: expr_with_numbers = expr.subs(var_dict)
In [6]: mathematica_code(expr_with_numbers).replace('==', '=')
Out[6]: '3*x^2 + 2*x + 1 = 5'
you can also solve for the expression easily:
In [7]: solve(expr_with_numbers, x)
Out[7]: [-1/3 + sqrt(13)/3, -sqrt(13)/3 - 1/3]
and you can print any kind of equation. For example
In [1]: from sympy import symbols, Eq, mathematica_code, sqrt, pretty, solve
In [2]: expr = Eq(a*(x**2)/(sqrt(x-c)), d)
In [3]: var_dict = dict(a=3, b=2, c=1, d=5)
In [4]: expr_with_numbers = expr.subs(var_dict)
In [5]: print(pretty(expr_with_numbers, use_unicode=False))
2
3*x
--------- = 5
_______
\/ x - 1
Pros
Useful, if you want to create complex mathematical expressions
Can also output pretty multiline output or even LaTeX output.
Can be useful if you want to actually solve the equation, too
Cons
Not speed-optimized for simple string formation.
You can avoid concatenating multiple strings using the format string python proposed.
Using Format strings vs concatenation to do a list of more performant to less performant
f-string as f"{a}x^2 + {b}x + {c} = {d}"
"%sx^2 + %sx + %s = %s" % (a,b,c,d)
"{}x^2 + {}x + {} = {}".format(a,b,c,d)
Might I suggest string interpolation?
given_parabola = "%sx^2 + %sx + %s = %s" % (a, b, c, d)
Or
given_parabola = f"{a}x^2 + {b}x + {c} = {d}"
Yes, hopefully, this is what you mean:
# This way the integer 10 will convert to a string automatically. Works in Print as well!
x = 10
y = "lemons"
z = "In the basket are %s %s" % (x, y)
print(z)
Output:
In the basket are 10 lemons

Solving multivariate equation for a subset of variables

I am using sympy to solve some equations and I am running into a problem. I have this issue with many equations but I will illustrate with an example. I have an equation with multiple variables and I want to solve this equation in terms of all variables but one is excluded. For instance the equation 0 = 2^n*(2-a) - b + 1. Here there are three variables a, b and n. I want to get the values for a and b not in terms of n so the a and b may not contain n.
2^n*(2-a) - b + 1 = 0
# Since we don't want to solve in terms of n we know that (2 - a)
# has to be zero and -b + 1 has to be zero.
2 - a = 0
a = 2
-b + 1 = 0
b = 1
I want sympy to do this. Maybe I'm just not looking at the right documentation but I have found no way to do this. When I use solve and instruct it to solve for symbols a and b sympy returns to me a single solution where a is defined in terms of n and b. I assume this means I am free to choose b and n, However I don't want to fix n to a specific value I want n to still be a variable.
Code:
import sympy
n = sympy.var("n", integer = True)
a = sympy.var("a")
b = sympy.var("b")
f = 2**n*(2-a) - b + 1
solutions = sympy.solve(f, [a,b], dict = True)
# this will return: "[{a: 2**(-n)*(2**(n + 1) - b + 1)}]".
# A single solution where b and n are free variables.
# However this means I have to choose an n I don't want
# to that I want it to hold for any n.
I really hope someone can help me. I have been searching google for hours now...
Ok, here's what I came up with. This seems to solve the type of equations you're looking for. I've provided some tests as well. Of course, this code is rough and can be easily caused to fail, so i'd take it more as a starting point than a complete solution
import sympy
n = sympy.Symbol('n')
a = sympy.Symbol('a')
b = sympy.Symbol('b')
c = sympy.Symbol('c')
d = sympy.Symbol('d')
e = sympy.Symbol('e')
f = sympy.sympify(2**n*(2-a) - b + 1)
g = sympy.sympify(2**n*(2-a) -2**(n-1)*(c+5) - b + 1)
h = sympy.sympify(2**n*(2-a) -2**(n-1)*(e-1) +(c-3)*9**n - b + 1)
i = sympy.sympify(2**n*(2-a) -2**(n-1)*(e+4) +(c-3)*9**n - b + 1 + (d+2)*9**(n+2))
def rewrite(expr):
if expr.is_Add:
return sympy.Add(*[rewrite(f) for f in expr.args])
if expr.is_Mul:
return sympy.Mul(*[rewrite(f) for f in expr.args])
if expr.is_Pow:
if expr.args[0].is_Number:
if expr.args[1].is_Symbol:
return expr
elif expr.args[1].is_Add:
base = expr.args[0]
power = sympy.solve(expr.args[1])
sym = expr.args[1].free_symbols.pop()
return sympy.Mul(sympy.Pow(base,-power[0]), sympy.Pow(base,sym))
else:
return expr
else:
return expr
else:
return expr
def my_solve(expr):
if not expr.is_Add:
return None
consts_list = []
equations_list = []
for arg in expr.args:
if not sympy.Symbol('n') in arg.free_symbols:
consts_list.append(arg)
elif arg.is_Mul:
coeff_list = []
for nested_arg in arg.args:
if not sympy.Symbol('n') in nested_arg.free_symbols:
coeff_list.append(nested_arg)
equations_list.append(sympy.Mul(*coeff_list))
equations_list.append(sympy.Add(*consts_list))
results = {}
for eq in equations_list:
var_name = eq.free_symbols.pop()
val = sympy.solve(eq)[0]
results[var_name] = val
return results
print(my_solve(rewrite(f)))
print(my_solve(rewrite(g)))
print(my_solve(rewrite(h)))
print(my_solve(rewrite(i)))

Formatting numbers in python

I am struggling to format some numbers in my python program. The users enters three numbers and then I put them into a formula. For example when the following numbers: 1 2 3, are entered on the command line, the output should look like this:
x**2+2x+3 = 0
Instead I am getting this: 1.0x**2+2.0x+3.0 = 0
How do I format it to loose the end decimals? I just want it to print out what was submitted. Here is some of my code:
a = float(sys.argv[1])
b = float(sys.argv[2])
c = float(sys.argv[3])
#to format equation
equation = ("{}x**2{}x{}".format(a,b,c))
you can type cast variable while formatting.
a = float(sys.argv[1])
b = float(sys.argv[2])
c = float(sys.argv[3])
equation = ("{}x**2{}x{}".format(int(a),int(b),int(c)))
print equation
Everyone elses answer doesn't allow for float inputs. There are 2 ways of doing this that I can think of:
a = float(sys.argv[1])
b = float(sys.argv[2])
c = float(sys.argv[3])
equation = ("{}x**2+{}x{}".format(str(a).rstrip('0').rstrip('.'),str(b).rstrip('0').rstrip('.'),str(c).rstrip('0').rstrip('.')))
print equation
This one takes away a 0 and a . from the end of each number if it exists.
a = float(sys.argv[1])
b = float(sys.argv[2])
c = float(sys.argv[3])
equation = ("{}x**2+{}x{}".format(sys.argv[1], sys.argv[2], sys.argv[3])
print equation
This one inserts exactly what the user inputted into the equation.
Just use int instead of float
import sys
a = int(sys.argv[1])
b = int(sys.argv[2])
c = int(sys.argv[3])
#to format equation
equation = ("({}x**2)+({}x)+({})".format(a,b,c))
print equation
I tried : python myfile.py -1 -2 3
output:
(-1x**2)+(-2x)+(3)

python: changing symbol variable and assign numerical value

In order to calculate derivatives and other expressions I used the sympy package and said that T = sy.Symbol('T') now that I have calculated the right expression:
E= -T**2*F_deriv_T(T,rho)
where
def F_deriv_rho(T,rho):
ret = 0
for n in range(5):
for m in range(4):
inner= c[n,m]*g_rho_deriv_rho_np*g_T_np
ret += inner
return ret
that looks like this:
F_deriv_rho: [0.0 7.76971e-5*T 0.0001553942*T**2*rho
T*(-5.14488e-5*log(rho) - 5.14488e-5)*log(T) + T*(1.22574e-5*log(rho)+1.22574e-5)*log(T) + T*(1.89488e-5*log(rho) + 1.89488e-5)*log(T) + T(2.29441e-5*log(rho) + 2.29441e-5)*log(T) + T*(7.49956e-5*log(rho) + 7.49956e-5)*log(T)
T**2*(-0.0001028976*rho*log(rho) - 5.14488e-5*rho)*log(T) + T**2*(2.45148e-5*rho*log(rho) + 1.22574e-5*rho)*log(T) + T**2*(3.78976e-5*rho*log(rho) + 1.89488e-5*rho)*log(T) + T**2*(4.58882e-5*rho*log(rho) + 2.29441e-5*rho)*log(T) + T**2*(0.0001499912*rho*log(rho) + 7.49956e 5*rho)*log(T)]
with python I would like to change T (and rho) as a symbol to a value. How could I do that?
So, I would like to create 10 numbers like T_def = np.arange(2000, 10000, 800)and exchange all my sy.symbol(T) by iterating through the 10 values I created in the array.
Thanks for your help
I have found the solution according to this post:
How to substitute multiple symbols in an expression in sympy?
by usings "subs":
>>> from sympy import Symbol
>>> x, y = Symbol('x y')
>>> f = x + y
>>> f.subs({x:10, y: 20})
>>> f
30
There's more for this kinda thing here: http://docs.sympy.org/latest/tutorial/basic_operations.html
EDIT: A faster way would be by using "lamdify" as suggested by #Bjoern Dahlgren

Categories