Python algorithm application of the stack of actual combat

Source: Internet
Author: User
Tags ord
What the stack is, you can understand as a first-in-a-out data structure, a linear table with restricted operations. The following article mainly introduces the application of Python in the actual combat, the text gives a number of examples, the need for friends can reference, the following to see together.

Stacks (Stack)

Stack is called the stack is a special ordered table, its insertion and deletion operations at the top of the stack, and follow the advanced, first-out rules to operate.

As shown

For example, the gun's magazine, the first bullet in the magazine is fired when the last one, and the last to put a bullet in the magazine when the first shot out.

The interface of the stack

If you create a stack, then you should have the following interface to perform the operation on the stack


Interface Description
Push () Into the stack
Pop () Out of the stack
IsEmpty () Determine if the stack is empty
Length () Get the length of the stack
GetTop () Take the element of the top of the stack, the element does not stack

Knowing that the stack requires the above interface, then in Python, the list is like a stack, providing the following interface:


Operation Description
s = [] Create a stack
S.append (x) Add an element inside the stack
S.pop () Delete an element within the stack
Not s Determine if the stack is empty
Len (s) Gets the number of elements within the stack
S[-1] Gets the element at the top of the stack

The stack interface in Python uses an instance:

# Create a stack in [1]: s = []# adds an element to the stack in [2]: S.append (1) in [3]: sout[3]: [1]# Delete an element within the stack in [4]: S.pop () out[4]: 1In [5]: Sout[5]: []# judgment stack is empty in [6]: not SOUT[6]: Truein [7]: S.append (1) in [8]: not SOUT[8]: false# Gets the number of elements in the stack in [9]: Len (s) out[9]: 1In [10 ]: S.append (2) in [All]: S.append (3) # Take the element in the top of the stack in [[]: s[-1]out[12]: 3

A big wave of examples

After understanding the basic concepts of stacks, let's look at a few more examples to make it easier to understand stacks.

Bracket Matching

Topic

If the expression is allowed to contain three brackets (), [], {}, its nesting order is arbitrary, for example:

The correct format

{()[()]},[{({})}]

Bad format

[(]),[()),(()}

Write a function that determines whether an expression string matches the correct parentheses

Ideas

    1. Create an empty stack to store the left parenthesis that have not been found;

    2. The convenience string, when encountering the opening parenthesis, presses the stack, encounters the right parenthesis and stacks an opening parenthesis to match;

    3. In the second step procedure, if the empty stack encounters a closing parenthesis, the description is missing an opening parenthesis and does not match;

    4. At the end of the second step traversal, the stack is not empty, indicating the absence of a closing parenthesis, mismatched;

Resolving code

It is recommended to break points in pycharm in order to better understand

#!/use/bin/env python# _*_ Coding:utf-8 _*_left = {' (', ' [', ' {'} # Left Parenthesis right = {') ', '] ', '} '} # closing parenthesis def match (expr): "" ": Param expr: The string passed: return: Returns whether the correct "" "stack = [] # Creates a stack for brackets in expr: # Iterates over all the strings if brackets in left: # if The current character is inside the opening parenthesis  stack.append (brackets) # puts the current opening parenthesis into the stack elif brackets in right: # If it is a closing parenthesis if not  stack or not 1 <= ord (brack ETS)-Ord (Stack[-1]) <= 2:  # If the current stack is empty, ()]  # If the closing parenthesis minus the opening parenthesis value is not less than or equal to 2 greater than or equal to 1 return  false # returns false  Stack.pop () # Remove opening parenthesis return not stack # returns TRUE if no value is in the stack, otherwise returns Falseresult = Match (' [() {()}] ') print (result)

Maze problem

Topic

A two-dimensional array to represent a simple maze, with 0 for the path, with 1 to block, the mouse at each point can move adjacent to the four points, design an algorithm, simulating the mouse maze, find a path from the entrance to the exit.

Out of the correct line in the red lines shown

Ideas

    1. Use a stack to record a mouse's path from the entrance to the exit.

    2. Go to a point, the point to the left side of the stack, and the point value of 1, indicating traversed;

    3. Select one of the reachable points from the nearest four points and go to that point;

    4. If you arrive at a point near the 4 points do not go, indicating that has gone into a dead end, at this time to withdraw the stack, back one step to try other points;

    5. Execute the combined second step repeatedly until the exit is found;

Resolving code

#!/use/bin/env python# _*_ coding:utf-8 _*_def initmaze (): "" ": Return: Initialize Maze" "" Maze = [[0] * 7 for _ in range (5 + 2)] # Create a 7*7 two-dimensional array with list parsing, to make sure that the maze is surrounded by walls walls = [# Records the location of the wall (1, 3), (2, 1), (2, 5), (3, 3), (3, 4), () (4, 2), and # ((4, 3), # If the point Set as a wall, then the entire maze is not going out, so it returns an empty list (5, 4)] for I in range (7): # Set the perimeter of the maze into a wall maze[i][0] = maze[i][-1] = 1 Maze[0][i] = Maze[-1][i ] = 1 for I, J in Walls: # Set the point of all walls to 1 maze[i][j] = 1 return Maze "" "[1, 1, 1, 1, 1, 1, 1][1, 0, 0, 1, 0, 0, 1][1, 1, 0, 0,  0, 1, 1][1, 0, 0, 1, 1, 0, 1][1, 0, 1, 0, 0, 0, 1][1, 0, 0, 0, 1, 0, 1][1, 1, 1, 1, 1, 1, 1] "" "Def Path (Maze, start, end):  "" ":p Aram Maze: Labyrinth:p Aram Start: Start point:p Aram End: End point: return: Each point of the walk" "" I, J = start # Decomposition starting point of the coordinate ei, ej = end # decomposition end point left stack = [(i, J)] # Create a stack and let the mouse stand at the starting point of the position maze[i][j] = 1 # walk through the road set to 1 while stack: # stack is not empty when continuing to walk, otherwise exit I, j = stack[-1] # Get the current mouse station Position point if (i, j) = = (EI, ej): Break # If the mouse finds an exit for Di, DJ in [(0,-1), (0, 1), (-1, 0), (1, 0)]: # Up or down if Maze[i + di][j + DJ] = = 0: # If the current point can walk mAze[i + di][j + dj] = 1 # Place the current point at 1 stack.append ((i + di, J + DJ)) # Add the current position to the stack break else: # If all the dots are not going to go Stack.pop () # Return the previous step return stack # returns empty stack if the maze cannot walk maze = Initmaze () # initialize the maze result = Path (Maze=maze, start= (1, 1), end= (5, 5)) # The mouse starts to walk the Maze Prin T (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)]

Suffix expression evaluation

Topic

When evaluating an expression, the compiler typically uses a suffix expression that 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 a suffix expression evaluation function.

Ideas

    1. Create a stack to store the operands to be calculated;

    2. Traversing the string, encountered the operand is pressed into the stack, encountered the operation symbol is the stack operand (n times), the corresponding calculation, the result is a new operand pressed back to the stack, waiting for the calculation

    3. According to the above procedure, the entire expression is traversed, and only the final result is left in the stack;

Resolving code

#!/use/bin/env python# _*_ Coding:utf-8 _*_operators = {# operator action table ' + ': lambda op1, Op2:op1 + op2, '-': Lambda OP1, Op2:o P1-OP2, ' * ': lambda OP1, OP2:OP1 * op2, '/': Lambda OP1, Op2:op1/op2,}def evalpostfix (E): "":p aram e: suffix expression: retur N: Normally the first element in the stack is the calculated value "" "Tokens = E.split () # Cut the suffix expression passed in to the list stack = [] for the token in tokens: # Iterate over the elements in the list if TOKEN.ISD Igit (): # If the current element is a number  stack.append (int (token)) # is appended to the stack elif token in Operators.keys (): # If the current element is operator  F = operators[ Token] # Gets the corresponding lambda expression in the Operator action table  OP2 = Stack.pop () # In accordance with the advanced post-out principle, first let the second element out of the stack  OP1 = Stack.pop () # in letting the first element out of the stack  Stack.append (f (OP1, OP2)) # puts the result of the calculation into the stack return Stack.pop () # returns the first element within the stack result = Evalpostfix (' 2 3 4 * + ') print (result) # 14

Knapsack problem

Topic

There is a backpack can be loaded with 10kg items, there are now 6 items, respectively:


Item Name Weight
Item 0 1kg
Item 1 8kg
Item 2 4kg
Item 3 3kg
Item 4 5kg
Item 5 2kg

Write to find all the solutions that can fill your backpack, such as items 1+ items 5.

Resolving code

#!/use/bin/env python# _*_ coding:utf-8 _*_def knapsack (t, W): "" ":p Aram T: Total backpack capacity:p Aram W: Item Weight list: return:" "" n = Len (w # Optional number of items stack = [] # Create a stack k = 0 # The currently selected item cursor while stack or K < n: # stack is not empty or k<n while T > 0 and K < n: # Also  There is space left and there is an item to install  if T >= W[k]: # The remaining space is greater than or equal to the current item weight  stack.append (k) # put the item backpack  T-= w[k] # backpack Space reduced  k + = 1 # keep looking backwards If T = = 0: # Find out about  print (stack) # fallback Process k = Stack.pop () # Take the last item out T + = w[k] # Backpack Total capacity plus w[k] k + = 1 # load the next item knapsack (1 0, [1, 8, 4, 3, 5, 2]) "" "[0, 2, 3, 5][0, 2, 4][1, 5][3, 4, 5]" ""

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.