Stack is a FirstInLastOut, a linear table with limited operations. The following article mainly introduces the practice of stack applications in Python. multiple instances are provided in this article. if you want to learn from them, let's take a look at them. Stack)
Stack, also known as Stack, is a special ordered Table. Its insert and delete operations are performed at the top of the stack and operate according to the rules of first-in-first-out and later-in-first-out.
As shown in
Example of using the stack interface in Python:
# Create a stack In [1]: s = [] # add an element In [2]: s. append (1) In [3]: sOut [3]: [1] # Delete an element In the stack [4]: s. pop () Out [4]: 1In [5]: sOut [5]: [] # judge whether the stack is empty In [6]: not sOut [6]: trueIn [7]: s. append (1) In [8]: not sOut [8]: False # obtain the number of elements In the stack In [9]: len (s) Out [9]: 1In [10]: s. append (2) In [11]: s. append (3) # get the element at the top of the stack In [12]: s [-1] Out [12]: 3
A large wave of instances
After understanding the basic concepts of stacks, let's look at several more instances to facilitate understanding stacks.
Matching Brackets
Question
If the expression can contain brackets (), [], and {}, the nested order is arbitrary. for example:
Correct format
{()[()]},[{({})}]
Incorrect format
[(]),[()),(()}
Compile a function to judge whether a expression string matches properly with parentheses.
Ideas
Create an empty stack to store unfound left brackets;
Convenience string. if the left bracket is used, the stack is pressed. if the right bracket is used, a left bracket of the stack is matched;
In the process of step 2, if there is an empty stack and the right parenthesis is encountered, it indicates that the left parenthesis is missing and does not match;
At the end of step 2 traversal, the stack is not empty, indicating that the right parenthesis is missing and does not match;
Solution code
We recommend that you break points in pycharm for better understanding.
#! /Use/bin/env python # _ * _ coding: UTF-8 _ * _ LEFT = {'(', '[', '{'} # LEFT brace RIGHT = {') ','] ','} # right brace def match (expr): "": param expr: passed string: return: returns whether "stack = [] # creates a stack for brackets in expr: # All strings passed by iteration if brackets in LEFT: # If the current character is in the left bracket, stack. append (brackets) # put the current left parenthesis into the stack elif brackets in RIGHT: # if it is a RIGHT brackets if not stack or not 1 <= ord (brackets) -ord (stack [-1]) <= 2: # if the current stack is empty, ()] # If the right brace minus the left brace value is not less than or equal to 2 or greater than 1 return False # False stack is returned. pop () # delete left parentheses return not stack # True is returned if there is no value in the stack, otherwise Falseresult = match ('[() {()}]') is returned. print (result)
Maze problems
Question
A two-dimensional array is used to represent a simple maze. 0 represents a path and 1 represents a blocking. rats can move four neighboring southeast-northwest points on each point to design an algorithm, simulate the mouse to walk through the maze and find a path from the entrance to the exit.
The red lines in the correct outgoing line are shown
Ideas
Use a stack to record the path of the mouse from the entrance to the exit
After going to a certain point, press the stack on the left of the point and set the value to 1, indicating that the point has passed;
Select any one of the four reachable points to go to the point;
If you do not go to the four nearest points after arriving at a certain point, it indicates that you have entered a dead end. at this time, you can roll back and try other points;
Perform steps 2, 3, and 4 until exit is found;
Solution code
#! /Use/bin/env python # _ * _ coding: UTF-8 _ * _ def initMaze (): ": return: initialize the maze "maze = [[0] * 7 for _ in range (5 + 2)] # use list parsing to create a 7*7 two-dimensional array, in order to ensure that the maze is surrounded by walls wballs = [# records the positions of the walls (1, 3), (2, 1), (2, 5), (3, 3 ), (3, 4), (4, 2), # (4, 3), # If you set (4, 3) to a wall, the entire Maze cannot go out, so an empty list (5, 4)] for I in range (7) is returned ): # set the four sides of the maze to the wall maze [I] [0] = maze [I] [-1] = 1 maze [0] [I] = maze [-1] [i] = 1 for I, j in Wils: # set the points of all walls to 1 maze [I] [j] = 1 return maze "[1, 1, 1, 1, 1, 1, 1, 1] [1, 0, 0, 1, 0, 0, 1] [1, 1, 0, 0, 0, 1, 1] [1, 0, 0, 0, 1, 1, 0, 1] [1, 0, 1, 0, 0, 0, 1] [1, 0, 0, 0, 0, 1, 0, 1] [1, 1, 1, 1, 1, 1, 1] "" def path (maze, start, end): ": param maze: param start: start point: param end: end point: return: each walking point "" I, j = start # coordinate of the starting point of decomposition ei, ej = end # stack on the left of the decomposition end point = [(I, j)] # Create a stack, and let the mouse stand at the starting position maze [I] [j] = 1 # set the path to 1 while stack: # continue when the stack is not empty; otherwise exit I, j = stack [-1] # obtain the location of the current mouse site if (I, j) = (ei, j): break # if the mouse finds the exit for di, dj in [(0,-1), (0, 1), (-1, 0), (1, 0)]: # left and right if maze [I + di] [j + dj] = 0: # If the current vertex can be maze [I + di] [j + dj] = 1 # set the current vertex to 1 stack. append (I + di, j + dj) # add the current position to the stack break else: # if all vertices cannot go through the stack. pop () # return to the previous return stack # if the Maze cannot go, return the empty stack maze = initMaze () # Initialize the Maze result = path (Maze = maze, start = (1, 1), end = (5, 5) # The Mouse begins to walk through the maze print (result) # [(1, 1), (1, 2), (2, 2 ), (3, 2), (3, 1), (4, 1), (5, 1), (5, 2), (5, 3), (4, 3), (4, 4), (4, 5), (5, 5)]
Suffix expression evaluate
Question
When calculating an expression, the compiler usually uses a suffix expression, which does not require parentheses:
Solution code
#! /Use/bin/env python # _ * _ coding: UTF-8 _ * _ operators = {# operator operation table '+': lambda op1, op2: op1 + op2 ,'-': lambda op1, op2: op1-op2, '*': lambda op1, op2: op1 * op2, '/': lambda op1, op2: op1/op2 ,} def evalPostfix (e): "": param e: suffix expression: return: Normally, the first element in the stack is the calculated value "" tokens = e. split () # split the passed suffix expression into the list stack = [] for token in tokens: # if token, an element in the iteration list. isdigit (): # if the current element is a digital stack. append (int (token) # append it to the stack. elif token in operators. keys (): # if the current element is the operator f = operators [token] # obtain the lambda expression op2 = stack in the operator table. pop () # first let the second element go out of the stack op1 = stack according to the principle of advanced and later. pop () # let the first element go out of the stack. append (f (op1, op2) # put the calculation result into the stack and return stack. pop () # return the first element in the stack result = evalPostfix ('2 3 4 * + ') print (result) #14
Backpack problems
Question
There is a backpack that can hold 10kg of items, and now there are 6 items:
Compile and find out all solutions that can fill your backpack, such as item 1 + Item 5.
Solution code
#! /Use/bin/env python # _ * _ coding: UTF-8 _ * _ def knapsack (t, w): ": param t: total backpack capacity: param w: item weight list: return: "" n = len (w) # Number of optional items stack = [] # Create a stack k = 0 # the currently selected item cursor while stack or k <n: # The stack is not empty or k
0 and k <n: # There is still space available and there are items that can be loaded if t> = w [k]: # The remaining space is greater than or equal to the current item weight stack. append (k) # equip the item with a backpack t-= w [k] # reduce the space of the backpack k + = 1 # continue to the back if t = 0: # Find print (stack) # Rollback process k = stack. pop () # take out the last item t + = w [k] # total backpack capacity plus w [k] k + = 1 # load the next item knapsack (10, [1, 8, 4, 3, 5, 2]) "[0, 2, 3, 5] [0, 2, 4] [1, 5] [3, 4, 5] ""
Summary
The above is all about this article. I hope this article will help you in your study or work. if you have any questions, please leave a message.
For more details about the Python algorithm application stack, refer to the PHP Chinese network!