测试C ++ postfix到中缀堆栈的太多操作数

问题描述 投票:2回答:1

我正在尝试测试是否有太多的操作数但无法弄清楚后缀表达式有太多操作数的条件。

有人可以给我任何关于测试内容的指示吗?

到目前为止,这是我的功能:

void evaluatePostFix(string str){
    Stack stack;
    // Strip whitespaces
    str.erase(str.find(' '), 1);
    if (str.length() == 1 || str.length() == 0){
        string singleOperand;
        singleOperand.push_back(str[0]);
        stack.push(createExpression("", singleOperand, ""));
    }
    int count = 0;

    for (const char & c : str){
        count++;
        if (isOperand(c)){
            string singleOperand;
            singleOperand.push_back(c);
            stack.push(singleOperand);
        } else {
            if (stack.isEmpty()){
                cout << "To many operators" << endl;
                return;
            }
            string operand1 = stack.top();
            stack.pop();
            if (stack.isEmpty()){
                cout << "To many operators" << endl;
                return;
            }
            string operand2 = stack.top();
            stack.pop();
            string operator1, expression;
            operator1.push_back(c);
            expression = createExpression(operand1, operand2, operator1);
            stack.push(expression);
        }
    }
    stack.print();
}
c++ algorithm stack postfix-notation infix-notation
1个回答
3
投票

我想你是在思考这个问题。要评估后缀表示法,请执行以下操作:

  1. 设置一个堆栈
  2. 迭代你的输入
  3. 如果你发现一个操作数将它推入堆栈
  4. 如果您发现某个操作弹出了从堆栈执行它所需的操作数数量。应用操作,然后将结果推回堆栈。如果你不能弹出正确数量的操作数而不是操作数太少。
  5. 在此过程结束时,您应该在堆栈中留下一个项目 - 结果。如果有多个项目,那么在某些时候你有太多的操作数。

这是一个可读的python实现来说明:

def evaluate_postfix(inputstr):

    # split into a list of parts consisting of operands and operators
    ops = inputstr.split()
    stack = []

    for i in ops:

        # if it's an operand push to the stack
        if i.isdigit():
            stack.append(int(i))
        else:
            # if there's not enough operands exit
            if len(stack) < 2:
                print("TOO FEW OPERANDS")
                exit()
            else:
                # pop the operands, apply the operation, and push the result
                a, b = stack.pop(), stack.pop()

                if i == '+': stack.append(a + b)
                elif i == '-': stack.append(a - b)
                elif i == '/': stack.append(a / b)
                else: stack.append(a * b)

    # if there are multiple values left in the stack then at some point
    # there were too many operands for the number of operations
    if len(stack) != 1:
        print("TOO MANY OPERANDS")
        exit()
    return stack[0]

还有一些测试用例:

print(evaluate_postfix("1 2 + 3 *"))
# 9
print(evaluate_postfix("1 2 + 3 * *"))
# TOO FEW OPERANDS
print(evaluate_postfix("1 2 3 4 + +"))
# TOO MANY OPERANDS
© www.soinside.com 2019 - 2024. All rights reserved.