A heap is a binary tree in which the value of each parent node is less than or equal to that of all its children, and the smallest element is always at the root of the binary tree.
import heapq import random data = range(10) random.shuffle(data) #Disorder order heap =  for n in data: heapq.heappush(heap,n) print heap heapq.heappushpop(heap,0.5) #New data in the heap heapq.heappop(heap) #Pop smallest element, heap rebuild
List to heap
myheap = [100,2,3,4,22,7,10,5] heapq.heapify(myheap) #Convert list to heap heapq.heapreplace(myheap,6) #Replace stack element value, heap rebuild heapq.nlargest(3,myheap) #Return the maximum 3 values heapq.nsmallest(3,myheap) #Minimum 3
The characteristics of the queue are First in first out, last in last out, First in first out, last in last out
import Queue q = Queue.Queue() q.put(0) #Element team q.put(1) q.put(2) print q.queue #deque([0, 1, 2]) print q.get() #Element 0 first out print q.queue() #deque([1, 2])
The features of the stack are Last in last out, first in last out, last in first out, first in first out
List can realize the basic operation of stack. append() is equivalent to in stack and pop() is equivalent to out stack. However, when the list is empty, the pop() operation will have exceptions and cannot limit the stack size.
import Stack x = Stack.Stack() x.push(1) x. push(2) x.show() x.pop() x.show()
class Stack: def __init__(self, size=10): self._content =  self._size = size def empty(self): self._content =  def isEmpty(self): if not self._content: return True else: return False def setSize(self,size): self._size = size def isFull(self): if len(self._content)==self._size: return True else: return False def push(self,v): if len(self._content)<self._size: self._content.append(v) else: print 'Stack Full' def pop(self): if self._content: return self._content.pop() else: print 'Stack is empty!' def show(self): print self._content def showRemainderSpace(self): print 'Stack can still PUSH',self.size-len(self._content),'elements.' if __name__=='__main__': print 'Please use me as a module'
You can directly use list and its basic operation to realize the function of linked list
linkTable =  linkTable.append(3) linkTable.append(5) linkTable.insert(1,4) linkTable.remove(linkTable)
5 binary tree