stack = []
def pushit():
stack.append(raw_input('enter new string: ').strip())
def popit():
if len(stack)==0:
print 'can not pop from an empty stack!'
else:
# 用反单引号(`)来代替repr()函数,把字符串的内容用引号括起来显示,而不是单单显示字符串的内容。
print 'removed [', `stack.pop()`, ']'
def viewstack():
print stack # calls str() internally
CMDs = {'u': pushit, 'o': popit, 'v': viewstack}
def showmenu():
pr = """
p(U)sh
p(o)p
(V)iew
(Q)uit
enter choice: """
while True:
while True:
try:
choice = raw_input(pr).strip()[0].lower()
except (EOFError,KeyboardInterrupt,IndexError):
choice = 'q'
print '\nyou picked: [%s]' % choice
if choice not in 'uovq':
print 'invalid option, try again'
else:
break
if choice == 'q':
break
CMDs[choice]()
if __name__ == '__main__':
showmenu()
参考文献:
1.《Python核心编程(第2版)》6.15;
2.用Python实现栈
更多推荐
《Python核心编程(第2版)》读书笔记(6)之用列表模拟堆栈(关键词:Python/列表/堆栈/stack.py)
发布评论