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

如何更简洁拆分数学表达式输入?求兼容负数的优化方案

优化方案:正则表达式实现(简洁高效+支持负数)

使用Python的re模块可以一行完成输入拆分,同时完美支持负数场景(包括开头负号、操作符后的负号),代码简洁且效率更高。

实现代码

import re

def main():
    user_input = input("What problem would you like solved?\nProblem: ")
    # 正则匹配:可选负号开头的数字,或操作符
    problem_list = re.findall(r'-?\d+|[+\-*/]', user_input)
    print(problem_list)

if __name__ == "__main__":
    main()

正则表达式说明

r'-?\d+|[+\-*/]' 的具体含义:

  • -?\d+:匹配带可选负号的数字,-?表示负号可有可无,\d+匹配一个或多个连续数字
  • |:逻辑或,匹配两侧任意一种模式
  • [+\-*/]:匹配任意一个算术操作符(+、-、*、/)

测试验证

  • 输入 10+2*5-534/2,输出 ['10', '+', '2', '*', '5', '-', '534', '/', '2'](符合预期)
  • 输入 -10+2*-5,输出 ['-10', '+', '2', '*', '-5'](正确识别负数)
  • 输入 10--2,输出 ['10', '-', '-2'](正确区分减号与负号)

原代码的问题修复与优化

如果不想依赖正则,也可以修复原代码的bug并扩展负数支持:

原代码问题点

  1. 循环结束后未处理剩余的str_build,比如输入10+2会漏掉末尾的2
  2. 无法区分减号和负号,比如-10会被拆成['-', '10']而非['-10']

修复后的代码

def check_for_sign(character: str) -> bool:
    return character in '+-*/'

def main():
    user_input: str = input("What problem would you like solved?\nProblem: ")
    str_build: str = ""
    problem_list: list = []
    index: int = 0
    length = len(user_input)

    while index < length:
        curr_char: str = user_input[index]
        # 处理负号:开头的-,或操作符后的-视为数字一部分
        if curr_char == '-' and (index == 0 or check_for_sign(user_input[index-1])):
            str_build += curr_char
            index += 1
            continue
        
        if not check_for_sign(curr_char):
            str_build += curr_char
        else:
            if str_build != "":
                problem_list.append(str_build)
            problem_list.append(curr_char)
            str_build = ""
        index += 1
    
    # 加入最后剩余的数字
    if str_build != "":
        problem_list.append(str_build)
    
    print(problem_list)

if __name__ == "__main__":
    main()

优化细节

  • 简化check_for_sign函数,用character in '+-*/'替代繁琐的match-case判断
  • 新增负号识别逻辑:当-位于输入开头,或前一个字符是操作符时,将其归为数字的一部分
  • 循环结束后补充处理剩余的str_build,修复末尾数字遗漏的bug

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 04:06:24