Я читаю книгу под названием Структура данных и алгоритм в Python .К сожалению, я застрял сейчас.
Речь идет о переписать строки в файле в обратном порядке, используя стек.
Вы можете игнорировать класс ArrayStack
, так как он только для сборки стека,Пожалуйста, смотрите функцию reverse_file.
''' Thanks Martineau for editing this to transform bunch of lines to code!'''
class Empty(Exception):
''' Error attempting to access an element from an empty container.
'''
pass
class ArrayStack:
''' LIFO Stack implementation using a Python list as underlying storage.
'''
def __init__(self):
''' Create an empty stack.
'''
self._data = [] # nonpublic list instance
def __len__(self):
''' Return the number of elements in the stack.
'''
return len(self._data)
def is_empty(self):
''' Return True if the stack is empty.
'''
return len(self._data) == 0
def push(self, e):
''' Add element e to the top of the stack.
'''
self._data.append(e) # new item stored at end of list
def top(self):
''' Return (but do not remove) the element at the top of the stack
Raise Empty exception if the stack is empty.
'''
if self.is_empty():
raise Empty('Stack is empty.')
return self._data[-1] # the last item in the list
def pop(self):
''' Remove and return the element from the top of the stack (i.e, LIFO)
Raise Empty exception if the stack is empty.
'''
if self.is_empty():
raise Empty('Stack is empty.')
return self._data.pop()
def reverse_file(filename):
''' Overwrite given file with its contents line-by-line reversed. '''
S = ArrayStack()
original = open(filename)
for line in original:
S.push(line.rstrip('\n'))
original.close() # we will re-insert newlines when writing.
# now we overwrite with contents in LIFO order.
output = open(filename, 'w')
while not S.is_empty():
output.write(S.pop() + '\n')
output.close()
if __name__ == '__main__':
reverse_file('6.3.text')
В книге сказано, что мы должны использовать метод .rstrip('\n')
, потому что в противном случае за последней строкой оригинала следует (без новой строки) вторая последняя строка с особым случаем.в котором файл не имеет пустой строки в финале - как вы знаете, pep8 всегда ловит вас с «без новой строки в конце файла».
Но почему это происходит?
Другоевсе строки в порядке, но почему только последняя строка имеет эту проблему?
Если '\n'
будет удален с помощью .rstrip('\n')
, почему имеет значение, имеет ли она новую строку в финале?