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

如何提取函数返回列表的元素供后续函数使用以实现多步运算RPN计算器

问题根因
  • 你的user_inputs函数存在提前返回的逻辑:只要匹配到两个数字加一个运算符的组合就直接返回输入列表,不会等待用户输入=,因此无法收集到完整的输入序列,后续的4、4、*、+这些内容根本不会被传入计算逻辑
  • calculation函数仅支持单次运算:没有循环处理所有输入的逻辑,也不会将中间运算结果留存到栈中参与后续计算,自然无法完成多步骤的RPN运算
修正后可直接运行的代码
def user_inputs():
    print("in inputs func:")
    operators = {'+', '-', '*', '/', '%', '='}
    inputs = []
    print("initial inputs: ", inputs)  
    while True:
        blank = input().strip()
        if blank == '=':
            inputs.append(blank)
            return inputs
        elif blank not in operators: # 处理数字输入
            try:
                inputs.append(int(blank))
                print("inputs: ", inputs)
            except ValueError:
                print("Unrecognised operator or operand ", blank)
        elif blank in operators: # 处理运算符输入
            inputs.append(blank)
            print("op inputs: ", inputs)


def calculation(inputs):
    stack = []
    operators = {'+', '-', '*', '/', '%'}
    for item in inputs:
        if isinstance(item, int):
            stack.append(item)
        elif item in operators:
            # 弹出栈顶两个数运算,注意RPN顺序是后弹出的是第一个操作数
            if len(stack) < 2:
                print("Operand insufficient")
                exit()
            op2 = stack.pop()
            op1 = stack.pop()
            if item == '+':
                res = op1 + op2
            elif item == '-':
                res = op1 - op2
            elif item == '*':
                res = op1 * op2
            elif item == '/':
                if op2 == 0:
                    print("Divide by 0.")
                    exit()
                res = int(op1 / op2)
            elif item == '%':
                if op2 == 0:
                    print("Divide by 0.")
                    exit()
                res = op1 % op2
            # 运算结果压回栈,参与后续运算
            stack.append(res)
        elif item == '=':
            # 遇到=直接返回栈顶结果
            final = stack[-1]
            if final >= 2147483647:
                return 2147483647
            elif final <= -2147483648:
                return -2147483648
            return final


while True: 
    print("\nRESULT:", calculation(user_inputs()), "\n")
关键修改说明
  • 移除了user_inputs中遇到运算符就提前返回的逻辑,仅当用户输入=时才返回全部输入,保证能拿到完整的运算序列
  • 重构了计算逻辑,采用标准RPN栈处理流程:数字压栈、遇到运算符弹出两个数运算后将结果压回栈,中间结果自动留存,不需要额外存储就能参与后续运算
  • 不需要在calculation内部重复调用user_inputs,只要一次性拿到所有输入按顺序处理即可满足需求,你给出的示例输入3、3、*、4、4、*、+、=运行后会正确返回25

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 16:54:01