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

来源:互联网 发布:北京sql培训 编辑:程序博客网 时间:2024/05/18 07:45
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() internallyCMDs = {'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实现栈

阅读全文
0 0
原创粉丝点击