Python data structures and algorithms - Stack

Stack

1. Definition: Stack of insertion, limiting the linear form and delete operations (known as stacks) on one end, allowing one end of the operation is called a "stack" and the other end is fixed is called "bottom of the stack", when the stack is not called "empty stack" time element.

2. Features:

  • Stack data operation only one end
  • Stack model is called the law of LIFO, or last-in first-out

3. Stack the code implementation

Stack has stack operation (push), the stack (popped), determination of full-empty stack operation.

1  "" " 
2  stack model sequentially stored
 three  key codes
 . 4  
. 5  ideas Analysis:
 6  1. That is sequentially stored list, but too many functions, do not meet the stack model
 7  interface method 2. Use of the list, the package type, providing the stack
 8  ' "" 
. 9  
10  #  custom exception class 
. 11  class StackError (exception):
 12 is    Pass 
13 is  
14  # sequence of stack type of packaging 
15  class SStack:
 16    DEF  the __init__ (self):
 . 17      #  property is empty list, which is the stack memory space 
18      # list of the last element is a top element 
. 19      self._elems = []
 20 is  
21 is   # Determines whether the stack is empty 
22 is    DEF is_empty (Self):
 23 is      return self._elems == []
 24  
25    #  stack elem 
26 is    DEF Push (Self, elem):
 27      self._elems.append (elem)
 28  
29    #  out stack 
30    DEF pOP (Self):
 31 is      # self._elems is empty if statement is true 
32      if  Not self._elems:
 33 is        the raise StackError ( " stack iS empty " )
 34 is      return self._elems.pop () #  pop-up list of the last a 
35 
36    #  See top element 
37 [    DEF Top (Self):
 38 is      IF  Not self._elems:
 39        The raise StackError ( " Stack IS empty " )
 40      return self._elems [-1 ]
 41 is  
42 is  IF  the __name__ == " __main__ " :
 43 is    SStack = ST ()   #  initialize stack 
44 is    st.push (10 )
 45    st.push (20 is )
 46 is    st.push (30 )
 47    the while  Not st.is_empty ():
48     print(st.pop())
Stack Model sequentially storing code
1  "" " 
2  linked storage stack
 3  key codes
 . 4  
. 5  ideas Analysis:
 6  1. Basic implementation model from list
 7  2. stack position?
 8  " "" 
9  #  custom exception class 
10  class StackError (Exception ):
 . 11    Pass 
12 is  
13 is  # node class 
14  class the node:
 15    DEF  the __init__ (Self, Data, Next = None):
 16      self.data = Data
 . 17      self.next = Next
 18 is  
. 19  # stack class of operation 
20 is  class LStack:
21   def __init__(self):
22     # 定义栈顶位置属性
23     self._top = None
24 
25   def is_empty(self):
26     return self._top is None
27 
28   def push(self,elem):
29     self._top = Node(elem,self._top)
30 
31   # 弹栈
32   def pop(self):
33     if self._top is None:
34       raise StackError("stack is empty")
35     val = self._top.data
36     self._top = self._top.next
37     return val
38 
39   # 查看栈顶值
40   def top(self):
41     if self._top is None:
42       raise StackError("stack is empty")
43     return self._top.data
44 
45 if __name__ == "__main__":
46   ls = LStack()
47   ls.push(10)
 48    ls.push (20 )
 49    ls.push (30 )
 50    print (ls.top ())
 51    ls.pop ()
 52    print (ls.top ())
Stack model chain store code

Exercise: a text, there may be paired brackets error. At least one bracket is inconsistent or
asked to write a code, this text detect abnormal writing brackets there
braces comprising {} [], ()

. 1  Import stack sequentially stored model (SStack)
 2  
. 3 ST = SStack ()
 . 4 the parens = " {} () [] "   # require authentication character 
. 5 left_parens = " {([ " 
. 6  # verify whether the pairing correct 
. 7 opposite_dict = { ' } ' : ' { ' ,
 8                   ' ] ' : ' [ ' ,
 9                   ' ) ' : ' ( '}
10 
11 
12 # Responsible for traverse 
13 is  DEF for_text (text):
 14    "" " 
15    traverse the string, and the character position to provide brackets
 16    : param STR:
 . 17    : return: listing the location and character of the bracket
 18 is    " "" 
. 19    # I is character index string, text_len length 
20 is    I, text_len = 0, len (text)
 21 is    the while True:
 22 is      # looping through the string 
23      # to the end of the end bracket is provided to meet Ver 
24      # If the length is greater than the index of the string and the string traversal cycle is not stopped in parens 
25      the while I <text_len and text [I] not  in parens:
 26 is       I + =. 1
 27      IF I> = text_len:
 28        return 
29      the else :
 30        the yield text [I], I
 31 is        I + =. 1
 32  
33 is  
34 is  # verification whether the character matches 
35  DEF Ver ():
 36    for PR, I in for_text (text):
 37 [      IF PR in left_parens:
 38 is        st.push_stack ((PR, I))   # left parenthesis stack 
39      elif st.is_empty_stack () or st.pop_stack () [0] =! opposite_dict [PR] :
 40       # The stack or the stack is null values in parentheses are not thrown by the corresponding dictionary 
41 is        Print ( " not matched positions of% d S% " % (I, PR))
 42 is        # for normal end loop 
43 is        BREAK 
44 is      the else :
 45        IF st.is_empty_stack ():
 46 is          Print ( " become " )
 47        the else :
 48          P = st.pop_stack ()
 49          Print ( " not matched position d of% S% " % (P [. 1 ], P [0 ]))
 50  
51 is  
52 is text = "dsfadsfa{d(sfa)dfa[dsf]}asdf"
53 # for pr, i in for_text(text):
54 #   print(pr, i)
55 
56 ver()
Exercise

Guess you like

Origin www.cnblogs.com/maplethefox/p/10988566.html