How do i solve an error on linear equation by python - python

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

Related

Error when trying to solve a quadratic? equation via python

First of all; english is not my main language so bare in mind. (The text in the script is in norwegian, I will try to translate as well as possible)
I am trying to create a python script that solves a second degree equation or a quadratic? equation I think. If i understand it correctly I should use cmath module to be able to solve complex roots, however, I havent got that far in my class yet and it is my task to only use math module and return a answer that looks something like this (if the roots are complex): "There is no real solution".
Also, when using normal math module I get returned a "math domain error" when trying to for example put a = 6, b = 11 and c = 32.
Thank you in advance.
Edward
Trying to use a if/elif/else thingy, have tried cmath (it returns a waaaay to long and unreadable answer)
My code is here under this (hopefully I have pasted it correctly, sorry in advance:
#Importerer math
import math
print("Programmet skal løse andregradslikningen ")
print("ax^2 + bx + c = 0 ved hjelp av abc-formelen")
print("Skriv inn verdiene for a, b og c.")
a = float(input('a = '))
b = float(input('b = '))
c = float(input('c = '))
d = (b**2) - (4*a*c)
sol1 = (-b+math.sqrt(d))/(2*a)
sol2 = (-b-math.sqrt(d))/(2*a)
if d < 0:
print("Likningen har ingen løsning")
elif d==0:
print(f"Løsning x = {-b/(2*a)}")
else:
print("Løsningen er")
print(f"x = {sol1}, og x= {sol2}")
You have to check if d is negative before you try to call math.sqrt(d), so you don't get an error.
d = (b**2) - (4*a*c)
if d < 0:
print("Likningen har ingen løsning")
elif d==0:
print(f"Løsning x = {-b/(2*a)}")
else:
sol1 = (-b+math.sqrt(d))/(2*a)
sol2 = (-b-math.sqrt(d))/(2*a)
print("Løsningen er")
print(f"x = {sol1}, og x= {sol2}")

While loops inside an if-statement?

Beginner programmer here:)) I am working on a school project, where the assignment is to find the roots to five functions in one file.
In one of my functions there are two roots, and my code can only find one. It seems like the second while-loop is ignored. I've tried to put only this code in a separate file, and it worked - but together with the other files it wont work...
Just ask if there is something that´s weird;)
def b(x: float):
return -x**2+x+6
def bgraf():
xlim(a1, b1)
ylim(-15, 25)
x = linspace(-5, 10, 1000)
y = b(x)
plot(x, y, 'r')
return
funksjoner = [0, 1, 2, 3, 4]
while response not in funksjoner:
i = int(input("choose a function from 0 to 4"))
response = i
if response in funksjoner:
print("you chose function ", int(funksjoner[i]))
a1 = float(input())
b1 = float(input())
z = a1
y = b1
m = a1
n = b1
NP = True
if int(funksjoner[i]) == funksjoner[1]:
while abs(y-z) > 1e-10:
null1 = (z+y)/2
if b(z)*b(null1)>0 and b(y)*b(null1)>0:
NP = False
print('No roots in this interval')
bgraf()
break
elif b(null1) == 0:
break
elif b(z)*b(null1)>0:
z = null1
else :
y = null1
while abs(n-m) > 1e-10:
null1_2 = (m+n)/2
if b(m)*b(null1_2)>0 and b(n)*b(null1_2)>0:
NP = False
print('No roots in this interval')
bgraf()
break
elif b(null1_2) == 0:
break
elif b(m)*b(null1_2)>0:
m = null1_2
else :
n = null1_2
if NP :
print('we have a root when x =', round(((z+y)/2), 1))
if null1 != null1_2:
print('and when x =', round(((m+n)/2), 1))
bgraf()
scatter(null1, 0)
if null1 != null1_2:
scatter(null1_2, 0)
It looks like python is ignoring the second while-loop I placed under the if-statement. Is there another way I could this?
Thanks for your attention!
Several things to think about:
what do you want to achieve with the following line of code:
If int(funksjoner[i]) == funksjoner[1]
You could simply check
If i == 1
i don‘t see any difference between the first and the second while loop.
z=m=a1
y=n=a2
So what should be the difference between those two?
In General the code is hard to read because of the naming of the variables, try to use variables which give you an impression what they contain.
For getting better impression what is going on in your code either use debugging, or if you are not familiar with debugging add print statements in your code to better understand what is stored in your variables at which time of the execution. And what statements are executed and which are skipped/not reached
When you give us more detailed information about your code (you could e.g. add comments to explain your code), have more detailed questions we can better support you

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)

Codechef - NZEC Error in python code

The code runs fine on my machine, but when i compile it on codechef it gives a NZEC(Runtime Error).
The link to the problem : https://www.codechef.com/problems/PPTEST
About my solution: I have calculated the percentile of each test case based on their time and point values. Then I have sorted the entries in each test case based on the percentile.
import sys
def check(x):
if not(x in range(1,100)):
sys.exit(1)
T = input()
check(T)
N_W = []
C_P_T = {}
tp = []
tt = []
for i in range(0,T):
tp.append(0)
tt.append(0)
N_W.append(map(int, raw_input().split()))
check(N_W[i][0])
check(N_W[i][1])
C_P_T[i] = []
for j in range(0,N_W[i][0]):
C_P_T[i].append(map(int, raw_input().split()))
check(C_P_T[i][j][0])
check(C_P_T[i][j][1])
check(C_P_T[i][j][2])
C_P_T[i][j].append(N_W[i][1]-C_P_T[i][j][2])
C_P_T[i][j].append(C_P_T[i][j][1]*C_P_T[i][j][0])
C_P_T[i][j].pop(0)
C_P_T[i][j].pop(0)
C_P_T[i][j].pop(0)
tp[i]+= C_P_T[i][j][1]
tt[i]+=C_P_T[i][j][0]
for i in range(0,T):
C_P_T[i].sort(key = lambda x : x[0] , reverse = True)
item_time = C_P_T[i][0][0]
percentile_time = (C_P_T[i][0][0]/float(tt[i]))*((len(C_P_T[i])-1)/float(len(C_P_T[i])))
for j in range(0,N_W[i][0]):
if C_P_T[i][j][0] == item_time:
C_P_T[i][j].append(percentile_time)
else:
item_time = C_P_T[i][j][0]
percentile_time = (C_P_T[i][j][0]/float(tt[i]))*((len(C_P_T[i])-j-1)/float(len(C_P_T[i])))
C_P_T[i][j].append(percentile_time)
for i in range(0,T):
C_P_T[i].sort(key = lambda x : x[1] , reverse = True)
item_points = C_P_T[i][0][1]
percentile_points = (C_P_T[i][0][1]/float(tp[i]))*((len(C_P_T[i])-1)/float(len(C_P_T[i])))
for j in range(0,N_W[i][0]):
if C_P_T[i][j][1] == item_points:
C_P_T[i][j].append(percentile_points)
else:
item_points = C_P_T[i][j][1]
percentile_points = ((C_P_T[i][j][1])/float(tp[i]))*((len(C_P_T[i])-j-1)/float(len(C_P_T[i])))
C_P_T[i][j].append(percentile_points)
C_P_T[i][j].append(C_P_T[i][j][2]+C_P_T[i][j][3])
C_P_T[i][j].append(N_W[i][1]-C_P_T[i][j][0])
C_P_T[i][j].pop(2)
C_P_T[i][j].pop(2)
C_P_T[i].sort(key = lambda x : x[2],reverse = True)
for i in range(0,T):
points = 0
for j in range(0,N_W[i][0]):
if N_W[i][1]-C_P_T[i][j][3] >= 0:
points+=C_P_T[i][j][1]
N_W[i][1]-=C_P_T[i][j][3]
print points
NZEC means "non-zero exit code", so that is probably happening in sys.exit(1) in your check() function. What you are receiving from input() is either not an integer or not in the right range.
Update: I notice that you use range(1, 100) for validity testing.
But the problem description at codechef states that 1 ≤ T ≤ 100. That is equivalent to range(1, 101)
So, codechef could be passing your code a perfectly valid 100, and your code would reject it, probably with the exact error you are seeing.

Categories