您的位置:首页 > 编程语言 > Python开发

《Python核心编程(第2版)》读书笔记(6)之用列表模拟堆栈(关键词:Python/列表/堆栈/stack.py)

2017-09-10 11:18 351 查看
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实现栈
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐