Python Stack Algorithm Implementation and simple application examples, python algorithm examples
This article describes the implementation and simple application of the Python stack algorithm. We will share this with you for your reference. The details are as follows:
Principle:
As a data structure, stack can only insert and delete data at one end. It stores data in accordance with the principle of first-in and second-out. The first data is pushed to the bottom of the stack, and the last data is on the top of the stack, data is popped up from the top of the stack when data needs to be read (the last data is read by the first one)
There are many application scenarios of NLP: 1. Stacks used in memory management; 2. binary tree traversal based on NLP; 3. symbol balance in language processing, in languages, many symbols appear in pairs, such as <>,{}, [], and (). One way to determine whether a symbol is missing is: assume that after reading a string, if the left part of the symmetric symbol is displayed, It is pushed into the stack. When the right part of the symmetric symbol is displayed, an object in the stack is displayed, if all the symbols are balanced, the stack should be empty at this time. By judging whether the stack is empty, it indicates whether the string is balanced.
In the sequence design, we need to define an instance attribute top. Three instance methods: get the top stack element peek (), pop (), push ()
Instance attribute: self. top. You must first find a Punctuation Point or a point that can be located as a benchmark.
Instance method:
1. Stack entry
Add node. next = top to the stack, and give a top
Top = node # After the node comes in, it is returned
Returns the top value.
2. Outbound Stack
1) whether the stack is empty or not. If yes, None is returned.
2) Otherwise, top. value is returned and top points to the next node.
To find a queue or stack, you need to find a node and your current location,
# For a vertex, we can know some content based on this vertex: class Node (object): def _ init _ (self): # the value of the located vertex and a point pointing to self. val = val # point to the value of the element, the second element of the original queue self. next = None # pointer to class stack (object): def _ init _ (self): self. top = None # initialize the start position def peek (self): # obtain the element if self at the top of the stack. top! = None: # return self if the top of the stack is not empty. top. val # return the value of the top element of the stack else: return None def push (self, n): # Add to stack n = Node (n) # instantiate Node n. next = self. top # pass the value of the top element to a pointer self. top = n # return n. val def pop (self): # exit stack if self. top = None: return None else: tmp = self. top. val self. top = self. top. next # Move one bit down and return tmpif _ name __= = "_ main _": s = stack () s. push (1) s. push (2) s. push (3) print s. pop () print s. pop () print s. pop ()
Print Effect
321
Application:
Number conversion:
1. Hard coding implementation
# -- Coding: utf-8 -- "N = input (" Please input a number: ") while (N ): print "** @ **" N-= 1 "N = input (" input decimal number (converted to octal )::") stack = [] string8 = "" while (N): # Calculate the remainder stack. append (N % 8) # quote N = N // 8 while (len (stack)> 0): string8 + = str (stack. pop () print "to octal:" + string8
2. Build a stack class to implement
Stack1.py
#--coding: utf - 8--class Stack(object): def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def GetTop(self): returnself.items[len(self.items) - 1]
Moshi. py
# -- Coding: utf-8 -- import stack1shiyan = stack1.Stack () stringu = "" temp = input ("enter a decimal number:") while (temp): shiyan. push (temp % 8) temp = temp/8 while (not shiyan. isEmpty (): stringu + = str (shiyan. pop () print ":" + stringu
Matching brackets
Hard coding implementation
# -- Coding: UTF-8 -- print "***** matching brackets *****" print "" input principle: Whenever you enter a bracket, you need to enter another ', ', for example: (, [,], (,). The input identifiable parentheses include (), [], {} "strpp = raw_input (" enter a bracket expression: ") basestr = strpp. split (',') pstack = [] suoyin = {'(': ')', '[': ']', '{': '} for e in basestr: if (e =' ('or e =' ['or e ='} '): pstack. append (e) else: if len (pstack) = 0: print "Parentheses (extra)" break else: if e = suoyin [pstack [len (pstack) -1]: pstack. pop () else: print "does not match" print "excessive right brackets" breakif len (pstack) = 0: print "correct match" else: print "excessive left brackets"