What is a data structure?
- Simply put, a data structure is how the design data is organized and stored in a computer.
- For example: Lists, collections, and dictionaries are data structures.
- N.wirth: "program = data structure + algorithm"
List
- Lists: called "arrays" in other programming languages, is a basic type of data structure.
- Questions about the list:
- How are the elements in the list stored?
- What are the basic actions that the list provides?
- What is the time complexity of these operations?
- List and mutable objects *
Stack
- A stack is a collection of data that can be understood as a list of inserts or deletions that can only be done at one end.
- Features of the stack: LIFO (last-in, first-out)
- The concept of stacks:
- Top of Stack
- Bottom of Stack
- Basic operation of the stack:
- Input stack (stack): push
- Out stack: Pop
- Take the top of the stack: gettop
Python implementations of Stacks
- You don't need to define yourself, you can use the list structure.
- In-Stack function: Append
- Out of stack function: Pop
- View Stack top function: li[-1]
Application of stack--bracket matching problem
- Parentheses match the question: give a string that contains parentheses, brackets, curly braces, to find out if the parentheses in the string match.
- For example:
- () () []{} match
- ([{()}]) match
- [] (Does not match
- [(]) mismatch
Bracket matching problem--implementation
1 defCheck_kuohao (s):2stack = []3 forCharinchS:4 ifCharinch{'(','[','{'}:5 stack.append (char)6 elifchar = =')':7 ifLen (Stack) > 0 andSTACK[-1] = ='(':8 Stack.pop ()9 Else:Ten returnFalse One elifchar = =']': A ifLen (Stack) > 0 andSTACK[-1] = ='[': - Stack.pop () - Else: the returnFalse - elifchar = ='}': - ifLen (Stack) > 0 andSTACK[-1] = ='{': - Stack.pop () + Else: - returnFalse + ifLen (stack) = =0: A returnTrue at Else: - returnFalseView Code
Application of stacks--maze problem
Give a two-dimensional list that represents the maze (0 means the channel, and 1 for the fence). Give the algorithm, find a path out of the maze.
Maze = [[1,1,1,1,1,1,1,1,1,1],
[1,0,0,1,0,0,0,1,0,1],
[1,0,0,1,0,0,0,1,0,1],
[1,0,0,0,0,1,1,0,0,1],
[1,0,1,1,1,0,0,0,0,1],
[1,0,0,0,1,0,0,0,0,1],
[1,0,1,0,0,0,1,0,0,1],
[1,0,1,1,1,0,1,1,0,1],
[1,1,0,0,0,0,0,0,0,1],
[1,1,1,1,1,1,1,1,1,1]
]
Solution Ideas
- On a maze node (x, y), you can probe in four directions: Maze[x-1][y], maze[x+1][y], maze[x][y-1], maze[x][y+1]
- Idea: Starting from a node, arbitrarily find the next point to go, when you can not find the point to go, back to the previous point to find whether there are other points of direction.
- Method: Create an empty stack and first place the entry position in the stack. When the stack is not empty loop: Get the top element of the stack, looking for the next adjacent block, if you can not find the adjacent square, indicating that the current position is a dead end, backtracking (that is, the current position out of the stack, to see if there are any other way to the front point)
Maze problem--stack implementation
1Dirs = [LambdaX, Y: (x + 1, y),LambdaX, y: (x-1, y),2 LambdaX, Y: (x, Y-1),LambdaX, Y: (x, y + 1)]3 defMgpath (x1, y1, x2, y2):4stack = []5 Stack.append ((x1, y1))6 whileLen (Stack) > 0:#loop when stack is not empty7Curnode = Stack[-1]#view top of stack elements8 ifCurnode[0] = = x2 andCurnode[1]:9 #reach the endTen forPinchStack: One Print(P) A Break - forDirinchdirs: -NextNode = Dir (*Curnode) the ifMG[NEXTNODE[0]][NEXTNODE[1]] = = 0:#found the next block. - stack.append (NextNode) -MG[NEXTNODE[0]][NEXTNODE[1]] = 1#marked as already traversed to prevent a dead loop - Break + Else: -MG[CURNODE[0]][CURNODE[1]] = 1#dead End + Stack.pop () A returnFalse
View Code
Queue
- A queue is a collection of data that is only allowed to be inserted at one end of the list and deleted at the other end.
- The one end of the insertion is called the tail of the queue (rear), and the Insert action is called the incoming or the queue
- The one end of the deletion is called the team header (front), and the delete action is called the queue
- Nature of the queue: FIFO (first-in, first-out)
- Two-way queue: Both sides of the queue allow incoming and outbound operations.
Implementation of the queue
- Can a queue be simply implemented in a list? Why?
- How to use: From collections import deque
- Create queue: Queue = Deque (LI)
- Incoming team: Append
- Out team: Popleft
- Two-way queue team first team: Appendleft
- Two-way Queue Team Tail Team: Pop
How the queue is implemented
- Initial assumptions: List + two subscript pointers
- Create a list and two variables, the front variable points to the head of the team, and the rear variable points to the tail. Initially, both the front and the rear were 0.
- Enter the operation: the element writes to Li[rear] position, rear increment 1.
- Out of action: Returns the element of Li[front], front 1.
- The problem of this realization?
How the queue is implemented--ring queue
- Improved scenario: Logically connect the list to the end.
How the queue is implemented--ring queue
- Ring queue: When the tail pointer front = = Maxsize + 1 o'clock, move forward one position automatically to 0.
- Implementation method: Calculating remainder
- Team first pointer forward 1:front = (front + 1)% MaxSize
- Team Tail hand forward 1:rear = (rear + 1)% MaxSize
- Team NULL Condition: rear = = Front
- Team Full Condition: (rear + 1)% MaxSize = = Front
Application of queues--maze problem
- Idea: Start with a node and look for all the points below to keep going. Keep looking until you find the exit.
- Method: Create an empty queue and enter the starting position into the team. Loop when the queue is not empty: out of the team once. If the current position is an exit, the algorithm is closed, otherwise the 4 adjacent squares of the current block can be found to walk in the block, all into the team.
Maze problem--queue implementation
1 defMgpath (x1, y1, x2, y2):2Queue =deque ()3Path = []4Queue.append (x1, y1, 1))5 whileLen (queue) >0:6Curnode =Queue.popleft ()7 path.append (Curnode)8 ifCurnode[0] = = x2 andCURNODE[1] = =y2:9 #reach the endTen Print(PATH) One returnTrue A forDirinchdirs: -NextNode = Dir (curnode[0], curnode[1]) - ifMG[NEXTNODE[0]][NEXTNODE[1]] = = 0:#find the next block theQueue.append (*nextnode, Len (path)-1)) -MG[NEXTNODE[0]][NEXTNODE[1]] = 1#marked as having traversed - returnFalse
View Code
Linked list
Each element in the list is an object, each of which is called a node and contains a data field key and a pointer to the next node next. Through the mutual connection between the nodes, the end is concatenated into a linked list.
Node Definition:
class Node (object): def __init__ (self, item): = Item = None
Head Knot Point
Traversal of a linked list
Insertion and deletion of linked list nodes
- Insert:
- P.next = Curnode.next
- Curnode.next = P
- Delete:
- p = Curnode.next
- Curnode.next = CurNode.next.next
- Del P
Create a linked list
- Head Interpolation method:
1 def Createlinklistf (LI): 2 L = node ()3for in li:4 s = node (num) 5 S.next = l.next6 l.next = s7 return l
View Code
Tail interpolation method:
1 def Createlinklistr (LI): 2 L = node ()3 r = L #R points to tail node 4 for in li:5 s = Node (num)6 r.next = s7 R = S
View Code
Double linked list
Each node in a doubly linked list has two pointers: one to the back node and one to the front node.
Node Definition:
1 class Node (object): 2 def __init__ (Self, item=None): 3 Self.item = Item4 self.next = None5 self.prior = None
View Code
Insertion and deletion of doubly linked list nodes
- Insert:
- P.next = Curnode.next
- CurNode.next.prior = P
- P.prior = Curnode
- Curnode.next = P
- Delete:
- p = Curnode.next
- Curnode.next = P.next
- P.next.prior = Curnode
- Del P
Create a doubly linked list
Linked List-analysis
- List and Linked lists
- Find by Element value
- Press the subscript to find
- Insert after an element
- Delete an element
Collections and dictionaries in Python (learn)
- Hash Table Lookup
- Hash table (hash table, also known as hash list) is a storage structure of linear tables. By using the keyword K for each object as an argument, the K is mapped to subscript h (k) by a hash function h (k), and the object is stored in this position.
- For example: Data set {1,6,7,9}, assuming that there is a hash function h (x) so that h (1) = 0, h (6) = 2, h (7) = 4, h (9) = 5, then this hash table is stored as [1,none, 6, None, 7, 9].
- When we look at the location of element 6, we get the subscript (H (6) = 2) of the element through the hash function h (x), so the element is found in the 2 position.
- There are many types of hash functions, and there is no further research here.
- Hash conflict: Because the subscript range of the hash table is limited, and the value of the element keyword is close to infinity, it is possible that H (102) = 2003, h () = 56 is the case. At this point, two elements are mapped to the same subscript, causing a hash conflict.
Resolve the hash conflict:
- Zipper method
- Connect all conflicting elements with a linked list
- Open addressing Method
- To get a new address through a hash conflict function
- Dictionary in Python: a = {' name ': ' Alex ', ' age ':-' gender ': ' Man '}
- Use the hash table store dictionary to map the key of the dictionary to subscript by using a hashing function. Suppose that H (' name ') = 3, H (' age ') = 1, H (' gender ') = 4, then the hash table is stored as [None, No, None, ' Alex ', ' Man ']
- In the case of a few dictionary key-value pairs, there is almost no hash conflict, where the time complexity of finding an element is O (1).
DAY40 Data Structure-algorithm (ii)