首页 > 解决方案 > 有没有办法从函数返回的列表中提取项目,然后在下一个函数中使用这些项目?

问题描述

我正在尝试创建一个 RPN 计算器

3
3
*
4
4
*
+
=

并在输入后返回结果=。到目前为止,我已经设法让它适用于个人表达,即

3
3
*
=

4
4
*
=

但我正在努力让它比存储第一个表达式的结果并计算第二个表达式更进一步,更不用说结合两个结果来获得最终结果了。

我已经改变了很多,但我目前的版本是这样的:

def user_inputs():
    print("in inputs func:")
    operators = {'+', '-', '*', '/', '%', '='}
    inputs = [0]
    print("initial inputs: ", inputs)  

while True:
        blank = input()
        if blank == '=':
            inputs.append(blank)
            return inputs
        elif blank not in operators: #if integer
            inputs.append(int(blank))
            print("inputs: ", inputs)
        elif blank in operators: #if operator
            inputs.append(blank)
            print("op inputs: ", inputs)

            checking = inputs[-3:]
            print("checking: ", checking)
            if type(checking[0]) is int and type(checking[1]) is int and checking[2] in operators:
                return inputs
        else:
            print("Unrecognised operator or operand ", blank)
            continue


def calculation(inputs):
    inputs = inputs()
    stack = []

    for a in inputs:
        stack.append(a)
        continue

    checking = stack[-3:]
    operators = {'+', '-', '*', '/', '%', '='}
    if type(checking[0]) is int and type(checking[1]) is int and checking[2] in operators:
        stack.pop()


    op2, op1 = stack[-1], stack[-2]
    print("op1 and op2: ", op1, op2)

    if '+' in inputs:    #code for addition
        result = op1 + op2
        stack.append(result)
                                         #user_inputs() position 1


    elif '-' in inputs: #code for subtraction
        result = op1 - op2
        stack.append(result)

    elif '/' in inputs: #code for division
        if op2 == 0: #if division by 0 is attempted
            print("Divide by 0.")
            exit()#see how to leave the function so that it doesnt crash
        else:
            result = int(op1 / op2)
            stack.append(result)

    elif '*' in inputs: #code for multiplication
        result = op1 * op2
        stack.append(result)

    elif '%' in inputs:
        if op2 == 0:
            print("Divide by 0.")
            exit()
        else:
            result = op1 % op2
            stack.append(result)


    if stack[-1] >= 2147483647:  # if above limit
        return 2147483647
    elif stack[-1] <= -2147483648: # if below limit
        return -2147483648
    else:
        return stack[-1]
                                                    #user_inputs() position 2


while True: 
    print("\nRESULT:", calculation(user_inputs), "\n")

我已经寻找方法来做到这一点,但没有找到我理解使用的任何东西。user_input()我正在考虑在内部调用calculation(),但后来我不知道在哪里适合放置它。当我尝试在位置 1 调用它时,它让我输入表达式的第二部分,但不会返回并进行计算。也许是因为我把它放在哪里?但我仍然不确定这种方法是否正确/是否可以做我想做的事。有没有办法再次获得输入并以某种方式返回到calculation()可以执行任何数学运算符的点?

标签: python

解决方案


推荐阅读