Detailed explanation of Python algorithm application practices and python algorithm practices
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
For example, the first bullet into the magazine is the last one when the gun is fired, at last, a bullet in the magazine was the first to be launched when it was hit.
Stack Interface
If you create a stack, you should have the following interfaces for Stack operations:
Interface |
Description |
Push () |
Inbound Stack |
Pop () |
Outbound Stack |
IsEmpty () |
Judge whether the stack is empty |
Length () |
Obtain the stack Length |
GetTop () |
Elements at the top of the stack are not included in the stack. |
After you know that the stack needs the above interface, the list in Python is similar to a stack. The interface provided is as follows:
Operation |
Description |
S = [] |
Create a stack |
S. append (x) |
Add an element to the stack |
S. pop () |
Delete an element from the stack |
Not s |
Judge whether the stack is empty |
Len (s) |
Obtain the number of elements in the stack. |
S [-1] |
Obtain the elements at the top of the stack |
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:
Infix expression |
Suffix expression |
2 + 3*4 |
2 3 4 * + |
(1 + 2) * (6/3) + 2 |
1 2 + 6 3/* 2 + |
18/(3*(1 + 2 )) |
18 3 1 2 + */ |
Write a program to implement the suffix expression evaluate function.
Ideas
- Create a stack to store the operations to be calculated;
- Traverse the string, press the operand into the stack, and return the stack operand (n times) when the operator symbol is encountered. The calculation result is that the new operand is pushed back to the stack, waiting for calculation.
- Based on the above process, the complete expression is traversed, and only the final result is left in the stack;
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:
Item Name |
Weight |
Item 0 |
1 kg |
Item 1 |
8 kg |
Item 2 |
4 kg |
Item 3 |
3 kg |
Item 4 |
5 kg |
Item 5 |
2 kg |
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 <n while t> 0 and k <n: # there is space available and there are items that can be loaded if t> = w [k]: # The remaining space is equal to or greater than the current item weight. 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.