如何实现支持代数项加减乘除的计算器:让程序识别并验证用户输入的代数表达式
解决代数表达式计算器的输入验证与加法实现
看起来你已经搭好了基础的ExpressionMaker类,接下来我们一步步搞定输入验证、实例转换和加法功能的问题——这些其实都可以通过正则表达式精准匹配格式,再配合类方法扩展来实现:
1. 用正则表达式实现输入格式验证与解析
你提到的输入顺序检查、系数/变量/幂的有效性验证,用正则表达式是最高效的方式。我们可以定义一个匹配正确代数项格式的正则,直接捕获三个要素,同时确保顺序正确:
正确格式的规则是:
- 系数:可选正负号的整数(比如
7、-3、+2) - 变量:单个大小写字母(比如
x、Y) - 幂:正整数(比如
1、3) - 顺序必须是:系数 → 变量 →
^→ 幂
对应的正则表达式是:^([+-]?\d+)([a-zA-Z])\^(\d+)$
我们来拆解一下这个正则:
^和$:确保整个输入字符串完全匹配,避免中间有多余字符([+-]?\d+):捕获系数,[+-]?表示可选正负号,\d+表示一个或多个数字([a-zA-Z]):捕获变量,匹配单个大小写字母\^:匹配字面量^(因为^在正则里有特殊含义,所以要转义)(\d+):捕获幂,匹配一个或多个数字
用Python的re模块来实现匹配和捕获:
import re def parse_algebraic_term(input_str): pattern = r'^([+-]?\d+)([a-zA-Z])\^(\d+)$' match = re.match(pattern, input_str.strip()) if not match: return None # 提取并转换三个要素 coefficient = int(match.group(1)) variable = match.group(2) power = int(match.group(3)) return ExpressionMaker(coefficient, variable, power)
这个函数会返回一个ExpressionMaker实例(如果输入正确),否则返回None。
2. 实现循环输入直到格式正确
接下来我们可以写一个循环,让用户重复输入直到格式正确:
def get_valid_expression(prompt): while True: user_input = input(prompt) term = parse_algebraic_term(user_input) if term: print(f"You entered: {term.term()}") return term else: print("Invalid format! Please enter a term like '7x^3' or '-2y^1'.")
调用这个函数就能得到一个合法的ExpressionMaker实例:
expression1 = get_valid_expression("What is your first algebraic expression?: ") expression2 = get_valid_expression("What is your second algebraic expression?: ")
3. 给ExpressionMaker类添加加法功能
代数项加法的核心规则是:只有变量和幂都相同的项才能相加,相加后系数合并,变量和幂保持不变。我们可以给ExpressionMaker类添加一个add方法:
class ExpressionMaker: def __init__(self, coefficient, variable, power): self.coefficient = coefficient self.variable = variable self.power = power def term(self): return "{}{}^{}".format(self.coefficient, self.variable, self.power) def add(self, other_term): # 检查是否是同变量同幂的项 if self.variable != other_term.variable or self.power != other_term.power: return f"Cannot add {self.term()} and {other_term.term()} - they have different variables or powers." # 合并系数,返回新的代数项实例 new_coeff = self.coefficient + other_term.coefficient return ExpressionMaker(new_coeff, self.variable, self.power)
现在就可以调用add方法来实现加法了:
result = expression1.add(expression2) if isinstance(result, ExpressionMaker): print(f"Addition result: {result.term()}") else: print(result)
完整代码示例
把所有部分整合起来,完整代码如下:
import re class ExpressionMaker: def __init__(self, coefficient, variable, power): self.coefficient = coefficient self.variable = variable self.power = power def term(self): return "{}{}^{}".format(self.coefficient, self.variable, self.power) def add(self, other_term): if self.variable != other_term.variable or self.power != other_term.power: return f"Cannot add {self.term()} and {other_term.term()} - they have different variables or powers." new_coeff = self.coefficient + other_term.coefficient return ExpressionMaker(new_coeff, self.variable, self.power) def parse_algebraic_term(input_str): pattern = r'^([+-]?\d+)([a-zA-Z])\^(\d+)$' match = re.match(pattern, input_str.strip()) if not match: return None coefficient = int(match.group(1)) variable = match.group(2) power = int(match.group(3)) return ExpressionMaker(coefficient, variable, power) def get_valid_expression(prompt): while True: user_input = input(prompt) term = parse_algebraic_term(user_input) if term: print(f"You entered: {term.term()}") return term else: print("Invalid format! Please enter a term like '7x^3' or '-2y^1'.") # 主程序 if __name__ == "__main__": expression1 = get_valid_expression("What is your first algebraic expression?: ") expression2 = get_valid_expression("What is your second algebraic expression?: ") result = expression1.add(expression2) if isinstance(result, ExpressionMaker): print(f"Addition result: {result.term()}") else: print(result)
这样就完成了你需要的所有功能:输入验证、格式检查、循环输入、代数项加法。你可以根据需求扩展乘法、除法功能,思路类似——先检查项的合法性,再执行对应运算规则。
内容的提问来源于stack exchange,提问作者Sean Balbuena
相关产品推荐
相关产品推荐

