用列表构建stack 和 队列

          最近对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 stack

CMDs = {'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 queue


CMDs = {'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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值