栈遵循后进先出原文,本文将用python 实现三个用栈的实例 栈在上一篇文章中已用python实现, 下面实例将引用这个栈。
1、实现一个文件中各行的逆置
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')) # we will re-insert newlines when writing
original.close()
# now we overwrite with contents in LIFO order
output = open(filename, 'w') # reopening file overwrites original
while not S.is_empty():
output.write(S.pop() + '\n') # re-insert newline characters
output.close()
2、实现在算数表达式中分隔符的匹配
算数表达式中有成对的符号,比如:
- 括弧 “(”和“)“
- 中括弧 “[”和“]”
- 花括弧 "{"和"}"
正确:(){[]}
错误:([{ ]})
from array_stack import ArrayStack
def is_matched(expr):
"""Return True if all delimiters are properly match; False otherwise."""
lefty = '({[' # opening delimiters
righty = ')}]' # respective closing delims
S = ArrayStack()
for c in expr:
if c in lefty:
S.push(c) # push left delimiter on stack
elif c in righty:
if S.is_empty():
return False # nothing to match with
if righty.index(c) != lefty.index(S.pop()):
return False # mismatched
return S.is_empty() # were all symbols matched?
3、测试一个函数是否有匹配标签
from array_stack import ArrayStack
def is_matched_html(raw):
"""Return True if all HTML tags are properly match; False otherwise."""
S = ArrayStack()
j = raw.find('<') # find first '<' character (if any)
while j != -1:
k = raw.find('>', j+1) # find next '>' character
if k == -1:
return False # invalid tag
tag = raw[j+1:k] # strip away < >
if not tag.startswith('/'): # this is opening tag
S.push(tag)
else: # this is closing tag
if S.is_empty():
return False # nothing to match with
if tag[1:] != S.pop():
return False # mismatched delimiter
j = raw.find('<', k+1) # find next '<' character (if any)
return S.is_empty() # were all opening tags matched?