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)
Related
I'm fairly new to python and i'm working on a problem for a school project. I feel im making progress but i'm not sure what to do next. The question is:
Write a function that takes mass as input and returns its energy equivalent using Einstein’s famous E = mc 2 equation. Test it with at least 3 different mass values. Write the program so that it can take the mass in kilograms as a commandline argument.
import sys
import math
m = float(sys.argv)
c = float(299792458)
def einstein_equation(m, c):
result = m * (math.pow(c, 2))
return result
e = einstein_equation(m, c)
print e
just make it simple man, no need for sys.argv
and no need for math.pow
just:
c = float(7382)
def einstein_equation(m, c):
return m * (c*c)
for _ in range(3):
m = float(input("MASS : "))
e = einstein_equation(m, c)
print (e)
You don't need libary for powering and just add index for sys.argv
import sys
m = int(sys.argv[1])
c = 299792458
print(m*c**2)
I know that you can avoid getting outputted, for example, 1e-10 using '{:.10f}'.format(1e-10), but I would adjust to take the decimal places as a variable (the 10f and e-10) depending on what the the value after e is...
I've used this code to find the value of decimal points needed
a = 6.789e-05
b = str(a)
if b[5] == 'e':
if b[7] == '0':
decimal_places = int(b[8])
else:
decimal_places = int(b[7]+b[8])
But I am struggling to figure out how I could no adjust the decimal places of the variable a using what I've found? As replacing '10f' with the decimal_places variable doesn't work... any help appreciated!
I've written a simple function to get number precission:
def precision(num):
n = str(num).split('e')
if len(n) == 1:
return 0
x = 0 if len(n[0].split('.')) == 1 else len(n[0].split('.')[1])
return x + abs(int(n[1]))
Then you can use string formatting to print your number to desired precission:
a = 6.789e-05
b = 6e-05
c = 3.5
d = 5
print('{num:.{precision}f}'.format(num=a, precision=precision(a))) # 0.00006789
print('{num:.{precision}f}'.format(num=b, precision=precision(b))) # 0.00006
print('{num:.{precision}f}'.format(num=c, precision=precision(c))) # 3.5
print('{num:.{precision}f}'.format(num=d, precision=precision(d))) # 5
I'm calling a matlab function in python through matlab engine, and I'm having problems to pass the variables.
I have figured out how to pass some, but for this on I'm getting an error. should be a scalar int.
but when I pass it I got the error:
File
"C:\ProgramData\Anaconda3\lib\site-packages\matlab_internal\mlarray_utils.py",
line 90, in _normalize_size
if init_dims[0] == 0:
IndexError: tuple index out of range
The code works fine If I do not pass the modn variable, so I know that my problem is the conversion type to matlab of this variable.
this is the python code:
import numpy as np
import matlab
import matlab.engine
eng = matlab.engine.start_matlab()
eng.cd()
Nn = 30
x= 250*np.ones((1,Nn))
y= 100*np.ones((1,Nn))
z = 32.0
xx = matlab.double(x.tolist())
yy = matlab.double(y.tolist())
f=np.arange(start=0.1,stop=0.66,step=0.1)
modnv=np.concatenate((np.ones((Nn)),2*np.ones((Nn))))
count = 0
for fks in f:
fks=np.float(0)
modn = modnv[count]
modn = modn.astype(int)
modn = matlab.int8(modn)
Output = eng.simple_test(xx,yy,z,fks,modn,nargout=4)
A = np.array(Output[0]).astype(float)
B = np.array(Output[1]).astype(float)
C = np.array(Output[2]).astype(float)
D = np.array(Output[3]).astype(float)
count = count + 1
and this is the matlab function simple_test:
function [A,B,C,D] = simple_test(x,y,z,fks,modn)
if modn == 1
A = 3*x+2*y;
B = x*ones(length(x),length(x));
C = ones(z);
D = x*y';
else
A = 3*fks;
B = 3*x+2*y;
C = A+B;
D = x*y'
end
Does someone know how to overcome that?
Whenever you get IndexError: tuple index out of range error its mostly:
Probably one of the indexes is wrong.I suspect you mean to say [0] where you say [1] and [1] where you say [2]. Indexes are 0-based in Python.
you are passing an array to a function that was expecting a variadic sequence of arguments (eg '{}{}'.format([1,2]) vs '{}{}'.format(*[1,2])
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)))
I am new to python programming and I'm getting runtime error with my code. Any help is appreciated.
import statistics
tc = int(input())
while tc > 0:
n = int(input())
arr = input()
l = list(map(int, arr.split(' ')))
print("{} {} {}".format(statistics.mean(l), statistics.median(l), statistics.mode(l)))
tc = tc - 1
Error
StatisticsError: no unique mode; found 2 equally common values
Input Format
First line consists of a single integer T denoting the number of test cases.
First line of each test case consists of a single integer N denoting the size of the array.
Following line consists of N space-separated integers Ai denoting the elements in the array.
Output Format
For each test case, output a single line containing three-separated integers denoting the Mean, Median and Mode of the array
Sample Input
1
5
1 1 2 3 3
Sample Output
2 2 1
You could add a variable mode surrounded by a try...except and if statistics has an error get the mode a different way.
try:
mode=statistics.mode(l)
except:
mode=max(set(l),key=l.count)
print("{} {} {}".format(statistics.mean(l), statistics.median(l), mode))
Hello Kartik Madaan,
Try this code,
Using Python 3.X
import statistics
from statistics import mean,median,mode
tc = int(input())
while tc > 0:
n = int(input())
arr = input()
l = list(map(int,arr.split()))
mod = max(set(l), key=l.count)
print(int(mean(l)),int(median(l)),mod)
tc = tc - 1
I hope my answer is helpful.
If any query so comment please.