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

编程知识 更新时间:2023-04-04 15:47:38


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)

本文发布于:2023-04-04 15:47:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/7267e151b12dc1735373ee733a092c79.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:堆栈   列表   之用   读书笔记   关键词

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!

  • 42913文章数
  • 14阅读数
  • 0评论数