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'm trying to improve my code so this is about a 'problem notification' telling me that a variable can be undefined.
This is my code:
print('\nWindow types')
print('1:1200 x 1300 mm')
print('2:800 x 1000 mm')
print('3:2100 x 1500 mm')
Window_Dimension = float(input('Select window type: '))
if Window_Dimension == 1:
A = 1200
B = 1300
elif Window_Dimension == 2:
A = 800
B = 1000
elif Window_Dimension == 3:
A = 2100
B = 1500
else:
print('Invalid input!')
Lip_height = float(input('\nEnter lip eight (mm): '))
SWind_velocity = 80 # m/s Static wind velocity
print('Assuming a peak wind velocity of: 80 m/s')
Wind_pressure = (SWind_velocity ** 2) / 1600 # kN/m^2
print('Wind pressure (kN/m^2):', Wind_pressure)
a = A - (2 * Lip_height)
b = B - (2 * Lip_height)
Lip_area = (A * B) - (a * b) # m^2
Lip_pressure = (Wind_pressure * (A * B) / 1000000) / (Lip_area / 1000000) # kN/m^2
print('Uniform pressure on the lip (kN/m^2): ', round(Lip_pressure, 3))
and it works just fine, but I keep getting a problem notification about this two lines:
a = A - (2 * Lip_height)
b = B - (2 * Lip_height)
telling me that A and B can be undefined. I don't know if there's is a way to fix this, or even if I should fix it, but I'm new in python and I'm trying to avoid future "coding bad habits". Thanks
Don't simply print an error message and proceed when something goes wrong. Throw an exception. Instead of
print('Invalid input!')
Consider
raise Exception('Invalid input!')
As far as I can tell, it works perfectly. I don't get any error. Perhaps you need to define the variables right at the beginning.
Right at the beginning, add this in:
a = 0
b = 0
This set the variables right at the beginning, without a calculation. Later on, it would only rewrite the variable, not create it.
Let me know if this worked!
Today, I've made a simple project about solving simple equation by python.
like this
linear="30=10x-20"
#c=bx+a or a+bx=c
a=0
c=0
b=0
split=linear.split("=")
if len(split[0])==1 or len(split[1])==1 :
c=int(split[0]) if len(split[0])==1 else int(split[1])
if len(split[0])>1 or len(split[1])>1 :
b=int(split[0][:linear.index("x")]) if len(split[0])>1 else int(split[1][:linear.index("x")])
a=int(split[0][linear.index("x")+1:] if len(split[0])>1 elseint(split[1[linear.index("x")+1:]))
total=(c-a)/b
print(total)
So, it separates the string between "=" first. Then, it analyzes the part of
separation to get the values of a,b,c. After that, I got the error. How do i fix this ?
thank you.
a=int(split[0][linear.index("x")+1:] if len(split[0])>1 else int(split[1][linear.index("x")+1:]))
ValueError: invalid literal for int() with base 10: ''
The if and else statements are confusing may be because of that you may be having this error. The things would be simpler if you learn regex in python.
I have tried with the given linear equation. Please use it as a reference.
import re
equation = '30=10x-20'
#Checking 'c = bx+a' or 'bx+a = c'
x = re.match('[0-9]+=[0-9]+x+?-?[0-9]+',equation)
if x:
#print('True')
output_1 = equation.split('=')
c = int(output_1[0])
print('c = ',c)
# checking the operator between bx and a
#rhs = '[0-9]+x+?[0-9]+'
y = re.match('[0-9]+x-?[0-9]+',output_1[1])
if y:
#filter_b = ['x']
output_2 = output_1[1].split('-')
a = int(output_2[1])
b = int(output_2[0].replace("x",""))
print('a = ',a)
print('b = ',b)
else:
print('False')
else:
print('False')
answer:
c = 30
a = 20
b = 10
I'm approaching this problem with little math experience and moderate python experience, any help appreciated.
I have these values and equations and need to find x and y:
x+y == a
a = 32.8
b = 19.3
c = 82
d = 12
e = 8
f = 69
f == ((((b+e)+x)*c)+(d*y))/(b+x+y)
Using sympy, I wrote the following code:
from sympy import symbols, Eq, solve, init_printing
a,b,c,d,e,f,x,y = symbols('a b c d e f x y')
init_printing(use_unicode=True)
expr = ((((b+e)+x)*c)+(d*y))/(b+x+y)
#I think this is x in terms of y
xiny = solve(expr.subs([(b,19.3), (c,82),(d,12),(e,8),(f,71)]),x)
# and I think this is y in terms of x
print(solve(eq.subs(a,32.8),y))
#But how to sub them in and continue?
Eq(f,expr)
eq = Eq(x+y,a)
solution = solve((eq.subs(a,32.8),expr.subs([(b,19.3), (c,82),(d,12),(e,8),(f,71)]) ),(x,y))
print(solution)
Using sympy I think I've managed to find x in terms of y, and y in terms of x but can't tie it all together. I'm getting negative numbers which don't make sense to me(especially for volumes which is the use case). What's the best way to approach this, especially as the a-f variables will be input by the user. Any help appreciated.
I've giving up the sympy syntaxe to focus on the math problem, so your system of equation you wanna solve is :
x+y = 32.8
((19.3+8+x)*82+12y)/(19.3+x+y) = 69
And I got the solution x = 9627/700 and y = 13333/700
If this solution is not correct than I guess there is a problem with the equation, or of course I can have solve it wrong
And in your sympy code, shouldn't it be more something like this :
expr = ((((b+e)+x)*c)+(d*y))/(b+x+y)
eq1 = Eq(f,expr)
eq2 = Eq(x+y,a)
solution = solve((eq2.subs(a,32.8),eq1.subs([(b,19.3), (c,82),(d,12),(e,8),(f,71)]) ),(x,y))
print(solution)
Interesting... Let's see. As I got you need to solve this system with a as parameter:.(It's made with https://codecogs.com/latex/eqneditor.php. May be it will help you to explain your tasks in future)
And code:
from sympy import *
a,b,c,d,e,f,x,y = symbols('a b c d e f x y')
init_printing(use_unicode=True)
a = 32.8 # you can put here a input() command
b = 19.3
c = 82
d = 12
e = 8
f = 69
# Note that "==" operator always returns bool, so this row does nothing
f == (((b+e+x)*c)+(d*y))/(b+x+y)
expr = ((((b+e)+x)*c)+(d*y))/(b+x+y)
eq1 = Eq(f,expr)
eq2 = Eq(x+y,a)
solve([eq1, eq2], (x,y))
{𝑥:13.7528571428571, 𝑦:19.0471428571429}
I found that you have defined your variables twice: in the begining ang in the subs method.
When you write solve(), it solves system of equations.
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)))