Inadvertently see a great God wrote "Linear equations Solver in 3 lines (python recipe)", the Python solution of a unary equation only three lines to complete, it is really tough ah.
Let's look around:
In the final analysis, the key to this piece of code is the use of complex numbers. The first step: 2 * x + 233 = x * 8 + 3 becomes 2 * x + 233-(x * 8 + 3) and then turns X into an imaginary 1j then becomes 2 * 1j + 233-(1j * 8 + 3) evaluates the result by Eval as 230-6j because we know that the expression knot The fruit is 0, and J is the equivalent of X. So the question becomes: 230-6j=0, which is 230-6x=0. Last x =-230/6 = 38.33333333336.
The core here is the use of Python's dark magic eval,eval The first argument is the expression, the second argument is the namespace, that is, the x = 1j through the second parameter to put some values in.
The Magic Solver function:
def s (eq, var= ' x '): r = eval (eq.replace (' = ', '-(') + ') ', {var:1j}) Return-r.real/r.imag |
This article link: http://everet.org/2012/04/linear-equations-solvers-in-python.html
(please indicate the author and source when reproduced.) )
Go Python's "dark Magic", two lines to solve one-dimensional equation