Python implements three lines of code to solve a simple one-dimensional equation-Python tutorial

Source: Internet
Author: User
Tags integer division
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.