我正在尝试使用堆栈反转在python的文本文件中编写的一些内容

时间:2019-06-11 08:29:21

标签: python stack

使用Python还原文本文件中的字符串

我尝试了下面的代码,因为我试图按相反的顺序进行推送,但没有返回

 import TStack as Stack


f=open('months.txt','r')

data=Stack.create()

for line in f:
    Stack.push(data,line)

while not Stack.is_empty(data):
    removed=Stack.pop(data)
    here=Stack.push(data,removed)

list returns None

1 个答案:

答案 0 :(得分:0)

您可以使用堆栈使用与反转行相同的过程来编写字符串反转:

import TStack as Stack

def reverse_string(s):
    stk = Stack.create()
    for c in s:
        Stack.push(stk, c)
    result = ""
    while not Stack.is_empty(stk):
        result += Stack.pop(stk)
    return result



f=open('months.txt','r')

data=Stack.create()

for line in f:
    Stack.push(data,line)

while not Stack.is_empty(data):
    print(reverse_string(Stack.pop(data)))

您还可以在将每一行添加到堆栈中时反转它们;

# ...

for line in f:
    Stack.push(data, reverse_string(line))

while not Stack.is_empty(data):
    print(Stack.pop(data))