【问题标题】:Evaluate postfix expression getting Wrong Output评估得到错误输出的后缀表达式
【发布时间】:2021-11-07 20:41:54
【问题描述】:

示例测试用例 测试用例 1: 预期输出: 输入·后缀·表达式231*+9- 结果·of·后缀·表达式·231*+9-·is·-4

测试用例 2: 预期输出: 输入·后缀·表达式34+22/* 结果·of·后缀·表达式·34+22/*·is·7

    class Evaluate:
        def __init__(self, capacity):
            self.top = -1
            self.capacity = capacity
            self.array = []
            
        def isEmpty(self):
            return True if self.top == -1 else False
        
        def peek(self):
            return self.array[-1]
            
        def pop(self):
            if not self.isEmpty():
                self.top -= 1
                return self.array.pop()
            else:
                return "$"
                
        def push(self, op):
            self.top += 1
            self.array.append(op)
            
        def evaluatePostfix(self, exp):
            for i in exp:
                
                if i.isdigit():
                    self.push(i)
                    
                else:
                    val1 = self.pop()
                    val2 = self.pop()
                    self.push(str(eval(val2 + i + val1)))
                    
            return int(self.pop())
            
    exp = input('Enter Postfix expression')
    obj = Evaluate(len(exp))
    print("Result of Postfix expression", exp , "is %d" % (obj.evaluatePostfix(exp)))


Test Case 1: Getting Correct Output = Result·of·Postfix·expression·231*+9-·is·-4
But in Test Case 2: I will get an Error


**Please let me know Where iam wrong...**

【问题讨论】:

    标签: python postfix-mta


    【解决方案1】:

    我运行了你的代码,它似乎给了我7.0 用于测试用例 2,所以它似乎工作。但是,字符串格式无法将7.0 转换为整数(%d),所以我收到此错误:

    Traceback (most recent call last):
      File "69147707.py", line 39, in <module>
        print("Result of Postfix expression", exp , "is %d" % (obj.evaluatePostfix(exp)))
      File "69147707.py", line 35, in evaluatePostfix
        return int(self.pop())
    ValueError: invalid literal for int() with base 10: '7.0'
    

    也许尝试使用 int() 将解决方案转换为 int?

    【讨论】:

    • 这没有回答问题。
    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-13
    • 1970-01-01
    • 2019-07-25
    • 2016-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多