我正在尝试测试是否有太多的操作数但无法弄清楚后缀表达式有太多操作数的条件。
有人可以给我任何关于测试内容的指示吗?
到目前为止,这是我的功能:
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();
}
我想你是在思考这个问题。要评估后缀表示法,请执行以下操作:
这是一个可读的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