最近對python 頗感興趣,買回來兩本書《python 核心程式設計》 和《利用python進行資料分析》 開始學習。
學習聯絡實踐,這樣效果最好,同時也想記載下我的學習歷程,所以開通了csdn的部落格。
下面就把書上講到的用列表實現堆疊和佇列的例子拿出來分享。
1-用列表模擬堆疊。
stack =def inpush():
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 =
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-列表實現佇列結構
queue =
def enq():
def deq():
if len(queue) == 0:
print 'cannot pop from an empty queue'
else:
print 'remove [',`queue.pop(0)`,']'
def viewq():
print queue
cmds =
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),先出第乙個元素。
棧(Stack)和佇列(Queue)
棧和佇列是兩種重要的線性結構。從資料結構角度看,棧和佇列也是線性表,其特殊性在於棧和佇列的基本操作是線性表操作的子集,它們是操作受限的線性表,因 此,可稱為限定性的資料結構。但從資料型別角度看,它們是和線性表大不相同的兩類重要的抽象資料型別。由於它們廣泛應用在各種軟體系統中,因此在物件導向 的程式設...
棧stack 和 佇列queue
stl中,sort的預設排序為less,也就是說從小到大排序 priority queue預設是less,也就說大頂堆 map預設是less,也就說用迭代器迭代的時候預設是小的排在前面 set預設是less,也就是說用迭代器迭代的時候是從小到大排序的。棧和佇列的區別是啥?吃多了拉就是佇列,吃多了吐就...
棧(stack)和佇列(queue)
棧的定義 特點 filo 是一種只能在一端進行插入或刪除操作的線性表。其中允許進行插入或刪除操作的一端稱為棧頂 top 棧頂由乙個稱為棧頂指標的位置指示器 對於順序棧,就是記錄棧頂元素所在陣列位置標號的乙個整型變數 對於鏈式棧,就是記錄棧頂元素所在結點位址的指標 來指示,它是動態變化的。表的另一端稱...