Python Postfix表示法堆栈类

时间:2018-04-02 16:12:05

标签: python stack postfix-notation

我不得不编写一个使用后缀表示法的Stack类来计算使用Python从文本文件输入的问题。我也想更新列表,不允许任何时候有超过10个项目。我相信,我的推送或流行方法似乎有些问题。任何建议都将不胜感激,谢谢。

更新了书面代码:

class Stack:
    #initializing the data
    def __init__(self):
        self.__data = [None] * 10
        self.__length = 0

    #destroying the existing stack
    def __destroy__(self):
        self.__data = [None] * 10
        self.__length = 0
        return

    #checking to see if the stack is empty
    def is_stack_empty(self):
        return self.__length == 0

    #checking to see if the stack is full
    def is_stack_full(self):
        if self.__length == 10:
            return True
        else:
            return False

    #pushing an item to the stack
    def push(self, item):
        try:
            self.__data.append(item)
            self.__length = self.__length + 1
            return
        except IndexError:
            print("ERROR: Cannot push more than 10 items to the stack.")


    #popping an item from the stack
    def pop(self):
        try:
            return self.__data.pop()
            self.__length = self.__length - 1
            return
        except IndexError: 
            print("ERROR: Cannot pop from an empty list.")


    #checking to see what the last item on the stack is
    def top(self):
        return self.__data[-1]

    #checking the length of the stack
    def __len__(self):
        return self.__length

    #overloading the string operator
    def __str__(self):
        return str(self.__data)





def main():
    file_name = input("Enter the name of the file containing postfix expressions: ")   
    #expression = input("Enter a mathmatical expression: ")
    #e_list = expression.split()
    #validates file
    found = False

    while not found:
        try:
            in_file = open(file_name)
            found = True
        except Exception as ex:
            print(file_name, " is not found.")
            file_name = input("Please re-enter a valid text file name: ")

    stack = Stack()

    for each in in_file:
        try:
            value = int(each)
        except Exception as ex:
            second = stack.pop()
            first = stack.pop()

            if each == "+":
                try:
                    answer = first + second
                    stack.push(answer)
                except Exception as ex:
                    print("ERROR: "+ expression + " is an invalid postfix expression.")
            elif each == "-":
                try:
                    answer = first - second
                    stack.push(answer)
                except Exception as ex:
                    print("ERROR: "+ expression + " is an invalid postfix expression.")  
            elif each == "*":
                try:
                    answer = first * second
                    stack.push(answer)
                except Exception as ex:
                    print("ERROR: "+ expression + " is an invalid postfix expression.")
            elif each == "/":
                try:
                    answer = first / second
                    stack.push(answer)
                except Exception as ex:
                    print("ERROR: "+ expression + " is an invalid postfix expression.")
        else:
            stack.push(value)
    print("Answer: ", stack.pop())


    return


main()

文件内容:

5 10 * 6 +
20 5 /
3 8 6 + *
3 4 + 9 - 12 +
9 3 2 1 + + /
3 + 5
* 3 4 5 + *
4 9 1 3 + -
h 3 +
0 1 2 3 4 5 6 7 8 9 10 11 12 + / - * + + + + + * * /

结果输出:

Enter the name of the file containing postfix expressions: expressions.txt
Expression:  5 10 * 6 +

Answer:  56

Expression:  20 5 /

Answer:  4.0

Expression:  3 8 6 + *

Answer:  42

Expression:  3 4 + 9 - 12 +

Answer:  10

Expression:  9 3 2 1 + + /

Answer:  1.5

ERROR: 3 + 5
is an invalid postfix expression.
Expression:  3 + 5

Answer:  5

ERROR: * 3 4 5 + *
is an invalid postfix expression.
Expression:  * 3 4 5 + *

Answer:  27

Expression:  4 9 1 3 + -

Answer:  5

ERROR: h 3 +
is an invalid postfix expression.
Expression:  h 3 +

Answer:  None

Expression:  0 1 2 3 4 5 6 7 8 9 10 11 12 + / - * + + + + + * * /
Answer:  0.0

预期产出:

Enter the name of the file containing postfix expressions: expressions.txt
Expression:  5 10 * 6 +

Answer:  56

Expression:  20 5 /

Answer:  4.0

Expression:  3 8 6 + *

Answer:  42

Expression:  3 4 + 9 - 12 +

Answer:  10

Expression:  9 3 2 1 + + /

Answer:  1.5

ERROR: 3 + 5 is an invalid postfix expression

ERROR: * 3 4 5 + * is an invalid postfix expression

ERROR: 4 9 1 3 + - is an invalid postfix expression

ERROR: h 3 + is an invalid postfix expression

ERROR: 0 1 2 3 4 5 6 7 8 9 10 11 12 + / - * + + + + + * * / is an invalid postfix expression

2 个答案:

答案 0 :(得分:0)

您将e_list替换为in_file,但它们不是一回事:前者是一个符号列表,如['5', '10', '*', '6', '+'],而后者是一个文件的迭代器,所以现在每个都是5 10 * 6 +,而不是字符串中的单个元素。

for expression in in_file:
    e_list = expression.split()
    for each in e_list:
        try:
            value = int(each)
        except ValueError as ex:
            second = stack.pop()
            first = stack.pop()

            # ...

答案 1 :(得分:0)

您的输入格式是一个行流,每个行都是由空格分隔的标记流组成一个表达式,如下所示:

5 10 * 6 +
20 5 /

但是您的代码会尝试将每一行视为一个令牌:

for each in in_file:
    try:
        value = int(each)

这里需要一个嵌套循环,内部循环在空格上分割,以按预期处理每一行的每个标记:

for line in in_file:
    for token in line.split():

目前尚不清楚是否应该为每个新行重置堆栈。如果是,您需要为每一行创建一个新的Stack

for line in in_file:
    stack = Stack()
    for token in line.split():

...或destroy每行末尾的堆栈,以便您可以重复使用它:

stack = Stack()
for line in in_file:
    for token in line.split():
        # etc.
    stack.__destroy__()

此外,您的Stack课程还有一个需要解决的严重问题。您的一些方法(__init__is_stack_full,)使用__data作为10个元素的固定大小的列表,并使用单独的__length来告诉您这些元素中有多少个是有效值,而其他人(__destroy__is_stack_emptytop__len____str__)使用__data作为0-10个元素的列表这些都是有效的,而其他人(pushpop)在同一方法中混淆了两者。您必须选择一个设计或另一个设计,并使用错误的方法修复方法。

作为一个小问题:您的__destroy__方法是由主代码调用的公共方法,而不是__init__之类的Python协议的实现,因此它应该被命名为destroy 。您的__data属性是常规的“按惯例”私有值,而不是您需要从超类和/或子类中隐藏以避免意外冲突的值,因此它应该是_data

当然,您的代码中可能存在其他错误,但这应该足以让您超越当前的障碍(以及您未预料到的下一个障碍)。