用列表构建stack 和 队列

来源:互联网 发布:linux系统克隆 编辑:程序博客网 时间:2024/05/16 11:36

          最近对Python 颇感兴趣,买回来两本书《Python 核心编程》 和《利用Python进行数据分析》 开始学习。

         学习联系实践,这样效果最好,同时也想记载下我的学习历程,所以开通了csdn的博客。

         下面就把书上讲到的用列表实现堆栈和队列的例子拿出来分享。

</pre></p><p>         1-用列表模拟堆栈。</p><p><pre name="code" class="html" style="white-space: pre;">stack = []def InPush():    stack.append((raw_input('Enter your String to push in : ' )).strip())    def OutPop():    if len(stack) == 0:        print 'Sorry ,your stack is empty,can not pop out any information'    else:        print ' Romove [', `stack.pop()` , ']'def ViewStack():    print stackCMDs = {'i':InPush ,'o':OutPop, 'v':ViewStack}def showmenu():    printmessege='''    (i)nPush    (o)utPop    (v)iew    (q)uit        Enter you choice : '''        while True:        while True:            try :                choice = raw_input(printmessege).strip()[0].lower()            except(EOFError,KeyboardInterrupt,IndexError):                choice = 'q'                                    print ' \n your choice is :[%s]' % choice                        if choice not in printmessege:                print 'Invalid choice ,Please look tips carfully!'            else:                break        if choice == 'q':            break        else:            CMDs[choice]()                        if __name__ == '__main__':    showmenu()    
   2-列表实现队列结构
 <pre name="code" class="python">queue = []def enQ():    queue.append(raw_input('Enter New string: ').strip())def deQ():    if len(queue) == 0:        print 'Cannot pop from an empty queue'    else:        print 'Remove [',`queue.pop(0)`,']'def viewQ():    print queueCMDs = {'e': enQ, 'd':deQ, 'v': viewQ}def showmenu():    pr = '''  (E)nqueue  (D)equeue  (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 '\n You picked: [%s]' %choice            if choice not in 'devq':                print 'Invalid option ,try again'            else:                break        if choice == 'q':            break        CMDs[choice]()if __name__ == '__main__':    showmenu()

     对于以上的两段代码,分别体现出了堆栈和队列的结构特点:堆栈先进后出,所以在str.pop()参数不写,默认就是弹出最后的元素,而队列是先进先出,所以str.pop(0),先出第一个元素。
     

0 0
原创粉丝点击