This article mainly introduces how to implement three lines of code in Python to solve a simple one-dimensional equation, which is suitable for beginners of Python to learn from, you can refer to the example described in this article to use three lines of code to solve the one-dimensional equation. the code is concise and efficient. the usage is as follows:
>>> Solve ("x-2 * x + 5 * x-46 * (235-24) = x + 2") 3236.0
The function code is as follows:
Def solve (eq, var = 'x'): eq1 = eq. replace ("=", "-(") + ")" c = eval (eq1, {var: 1j}) return-c. real/c. imag
Let's explain the code below.
The first line is the first line, which transforms the equation and generates a formula "x-2 * x + 5 * x-46 * (235-24)" with the result 0) -(x + 2 )".
The second row uses eval to execute this formula, and x = 1j is substituted into the formula. The result is-9708 + 3j.
Note that x = 1j, so this equation is reduced to "-9708 + 3x = 0". you only need to convert-(-9708)/3 to get x.
-9708 is the real part of the complex number, and 3 is the virtual part of the complex number, so the result is "-c. real/c. imag ".
Obviously, this function cannot solve the complex number equation.
By the way, the/operation of Python 2.x uses integer division, leading to the loss of the fractional part. Therefore, Python 3.xshould be used to obtain the correct result.
I hope this example will help you learn Python.