You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用原生Python提取代数等式左右两侧x的系数?

Hey there! Great question—extracting coefficients for x (even when they’re complex expressions like (2*3+4)x) is totally doable with native Python, and eval() is indeed a useful tool here. Let’s break this down step by step.

Core Idea

For linear expressions (which I assume you’re working with, since you’re extracting a single coefficient for x), the coefficient of x is equal to:
value of expression when x=1 minus value of expression when x=0

Why? Because any linear expression can be written as Ax + B. When x=1, it becomes A + B; when x=0, it becomes B. Subtracting these gives you A—exactly the coefficient we need.

The Catch: Properly Replacing x

The tricky part is replacing x with 1 or 0 without breaking expressions like 3x (which should become 3*1, not 31) or -x (which should become -1, not -0). We’ll use Python’s built-in re module to handle these edge cases with regex.

Full Solution Code

First, here’s the helper function to extract the coefficient from a single side of the equation, then we’ll integrate it with your existing input handling:

import re

def get_x_coefficient(expr):
    # Replace x with 1 correctly (handle cases like "x", "3x", "-x", "(2+3)x")
    expr_x1 = re.sub(r'(?<![0-9)])x', '1', expr)  # Replace standalone x (no number/bracket before) with 1
    expr_x1 = re.sub(r'x', '*1', expr_x1)         # Replace remaining x (with number/bracket before) with *1
    
    # Replace x with 0 correctly
    expr_x0 = re.sub(r'(?<![0-9)])x', '0', expr)  # Replace standalone x with 0
    expr_x0 = re.sub(r'x', '*0', expr_x0)         # Replace remaining x with *0
    
    try:
        # Calculate the two values and find the difference (this is our coefficient)
        val_x1 = eval(expr_x1)
        val_x0 = eval(expr_x0)
        return val_x1 - val_x0
    except Exception as e:
        raise ValueError(f"Could not parse expression: {expr}") from e

# Your existing input handling code
equation = input("Enter equation: ")
LHS, RHS = equation.split("=")[0], equation.split("=")[1]
# Remove whitespaces
LHS, RHS = LHS.replace(" ", ""), RHS.replace(" ", "")

# Get coefficients for both sides
lhs_coeff = get_x_coefficient(LHS)
rhs_coeff = get_x_coefficient(RHS)

# Total coefficient after moving all terms to the left side (LHS - RHS = 0)
total_x_coefficient = lhs_coeff - rhs_coeff

print(f"Coefficient of x on LHS: {lhs_coeff}")
print(f"Coefficient of x on RHS: {rhs_coeff}")
print(f"Total x coefficient (LHS - RHS): {total_x_coefficient}")

Testing Examples

Let’s verify with some common cases:

  • Input: (2*3+4)x -7 = x +3
    • LHS coefficient: 10 (since (2*3+4)=10)
    • RHS coefficient: 1
    • Total coefficient: 10 - 1 = 9
  • Input: -x = 5
    • LHS coefficient: -1
    • RHS coefficient: 0
    • Total coefficient: -1 -0 = -1
  • Input: 2x +3x -5 = 4
    • LHS coefficient: 5 (2+3)
    • RHS coefficient:0
    • Total coefficient:5-0=5

Important Notes

  • Linear Assumption: This works for linear expressions (only x to the first power). If you need to handle higher powers (like x²), this method won’t work—you’d need a more complex parser.
  • Security: Be cautious with eval() if this solver will handle untrusted input. eval() executes arbitrary code, so it’s safe only if you control the input source.
  • Valid Expressions: The function assumes well-formed algebraic expressions (no syntax errors, consistent use of x for the variable).

内容的提问来源于stack exchange,提问作者Sujal Motagi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 11:42:36