python learning 3--python complex data types

Keywords: Python less

1 piles

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.

Heap creation

import heapq
import random
data = range(10)
random.shuffle(data) #Disorder order
heap = []
 for n in data:
 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

2 queue

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
 print q.queue #deque([0, 1, 2])
 print q.get() #Element 0 first out
print q.queue() #deque([1, 2])

3 stack

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(2)
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
             return False
     def setSize(self,size):
         self._size = size
     def isFull(self):
         if len(self._content)==self._size:
             return True
             return False
     def push(self,v):
         if len(self._content)<self._size:
             print 'Stack Full'
     def pop(self):
         if self._content:
             return self._content.pop()
             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'

4 list

You can directly use list and its basic operation to realize the function of linked list

linkTable = []

5 binary tree


6 digraph


Posted by Waire on Tue, 05 May 2020 02:21:30 -0700