-1

I am trying to make an algebra solver, so I have to find the coefficients of x in an expression. Currently this is the code I have to take an input:

equation = input("Enter equation: ")
LHS, RHS = equation.split("=")[0], equation.split("=")[1]

##Remove whitespaces
LHS, RHS = LHS.replace(" ",""), RHS.replace(" ","")

Now I want to get the coefficients of x in the expressions LHS and RHS, how can I do this? And also, the coefficients may not be just numbers but they may be of the form (2*3+4)x. I think this can be done using the eval() function but I don't know how to apply it.

Note: I want to do this with plain python, without using any modules which are not built-in.

Sujal Motagi
  • 145
  • 8

1 Answers1

0

In case it's only one variable and thus only one coefficient you could divide the respective variable/site by x. Taking your example:

(2*3+4)x

dividing by x gives us the coefficient:

(2*3.4)

If that's not the approach you want to take, you could also convert the expression into a string and exclude "x", as such:

coefficientLHS = LHS.replace("x", "")

However, you should use this cautious as you might have algebra expressions in front of your variable, so regex implementation would be advisable.

Another approach would be to use the module Poly:

x = symbols("x")
coefLHS = Poly(LHS, x)
coefLHS.coeffs()
J. Doe
  • 61
  • 1
  • 2
  • 9