Application of data structure [Python--stack]

Source: Internet
Author: User
Tags mul

It is rare to have some free, look at the data structure of Python--stack, now a few typical examples to summarize!

First, what is the stack

The stack is an ordered set, according to its characteristics can be called "advanced post-out" or "LIFO", where the addition or deletion occurs on the same side, this end is called "Stack Top", and its corresponding called "bottom".

The bottom of the stack is important because the data stored at the bottom is the longest, and the most recent additions always pop up first, which is sometimes called "LIFO"

Second, stack

1. Operations available on the stack

  • Stack()Creates a new, empty stack. It does not require parameters and returns an empty stack.

  • push(item)Adds a new item to the top of the stack. It needs to item make a parameter and does not return any content.

  • pop()Removes the top item from the stack. It does not require parameters and returns item . Stack is modified.

  • top()Returns the top item from the stack, but does not delete it. No parameters are required. Does not modify the stack.

  • isEmpty()Whether the test stack is empty. No arguments are required and a Boolean value is returned.

  • size()Returns the number in the stack item . No arguments are required and an integer is returned.

  • clearEmpty stack, no return value

2. Use Python's built-in data structure list to implement all stack operations

Class Stack (): Def __init__ (self): Self.itmes = [] def isEmpty (self): return self.itmes = = [] def c Lear (self): del self.itmes[:] def push (self, item): Self.items.append (item) def pops (self): Retu RN Self.itmes.pop () def top (self): return self.items[-1] def size (self): return len (self.itmes)

3. Examples of use of stacks

3.1 Binary conversions

Class stack ():     def __init__ (self):         self.itmes = []    def isempty (self):         return self.itmes == []    def clear (self):         del self.itmes[:]    def push (Self,  item):         self.items.append (item)     def  pop (self):         return self.itmes.pop ()      def top (self):        return self.items[-1]     def size (self):         return len ( Self.itmes) Def divideby2 (decnumber, base):     remstack = stack ()      while decnumber > 0:        rem = decnumber %  Base        remstack.push (REM)          decNumber = decNumber // base    binString =  ""     while not remstack.empty ():         Binstring = binstring + str (Remstack.pop ())     return binstringif  __name__ ==  ' __main__ ':     print (DivideBy2 (42, 2))

Description: This is the "stack" implemented with the list structure, and we can write a stack ourselves

3.2 Write your own stack

class node:    def __init__ (Self, value):         self.value = value        self.next =  noneclass stack:    def __init__ (self):         self.top = none    def push (Self, value):         node = node (value)          node.next = self.top        self.top =  node    def pop (self):         node  = self.top        self.top = node.next         return node.values = stack () S.push (3) s.push (' AC ') S.push (' er ') s.pop () S.push (5)

Description

    1. The stack above is defined by the top pointer pointing to a complete node instance

    2. Defines a stack that uses pointers to control where it is read.

3.3-Stack application--prefix expression (Polish style)

From __future__ import divisionclass node ():     def __init__ (self ,  value):        self.value = value         self.next = noneclass stacknode ():     def  __init__ (self):        self.top = none     def push (Self, value):        node =  Node (value)         node.next = self.top         self.top = node    def pop (self):         node = self.top         self.top = node.next        return node.valuedef  Compute_exec (OP, OV1, OV2):     def add (OV1, OV2):         return ov1 + ov2    def sub (OV1, OV2):         return ov1 - ov2    def mul (ov1,  OV2):        return ov1 * ov2     Def div (OV1, OV2):         return ov1 / ov2     ops = {add:  ' + ', sub:  '-', mul:  ' * ',  div:   "/"}    for k, v in ops.items ():         if v == op:             ret = k (OV1, OV2)              Stack1.push (ret)   &nbsP;         breakdef perfix_reverse (String):   #  reverse    tmp =  '     for s in string[ ::-1]:        if s ==  "(":             tmp +=  ")"          elif s ==  ")":             tmp  +=  "("         else:             tmp += s    return tmpdef infix_to _prefix (String):    opt =  '     string_tmp =  Perfix_reverse (String)     for i in string_tmp:  #   Prefix-expression     &nbSp;   if i.isdigit ():             opt = i + opt        elif i !=   ':             stack1.push (i)          elif i ==  ")":             opt = stack1.pop ()  + opt             stack1.pop ()     for s in opt[::-1]:         if s.isdigit ():             stack1.push (s)         else:                 op1 = s                 ov1 = stack1.pop ()                  ov2 = stack1.pop ()                 compute_exec ( Op1, int (OV1),  int (OV2))   # compute result                  continue    return  Opt, stack1.pop () if __name__ ==  ' __main__ ':    stack1 =  Stacknode ()   #  operator     infix = [' ((3+4) * *) ',  ' ((4*2)-1) ',   ' (5* (1+2)) ']    for i, v in enumerate (infix):         print infix[i],  "==>",  infix_to_prefix (v)

Description

    1. The prefix expression means that the operator is before the operand

    2. An expression is parsed from right to left. The value of the stack, encountered the symbol will be the top of the stack and the sub-position popup to calculate, the result is again into the stack until the expression parsing is complete.

3.4-Stack application-suffix expression (inverse Polish style)

Class node ():     def __init__ (Self, value):         self.value = value        self.next =  noneclass stacknode ():     def __init__ (self):         self.top = none    def push (Self, value):         node = node (value)          node.next = self.top        self.top  = node    def pop (self):         node  = self.top        self.top = node.next         return node.valuedef compute_exec (OP, OV1, OV2):     def adD (OV1, OV2):        return ov1 + ov2     def sub (OV1, OV2):         return ov1 -  ov2    def mul (OV1, OV2):         Return ov1 * ov2    def div (OV1, OV2):         return ov1 / ov2    ops = {add:  ' + ',  sub:  '-', mul:  ' * ', div:  '/'}    for k, v in  ops.items ():        if v == op:             ret = k (OV1, OV2)              stack1.push (ret)            &nBsp; breakdef postfix (expr):    for s in expr:         if s.isdigit ():             stack2.push (s)         elif s !=  ": "            stack1.push (s)          elif s ==  ")":             top = stack2.pop ()              snext = stack2.pop ()              Stack2.push (". Join ([Snext, top, stack1.pop ()]))              stack1.pop ()     post_expr = stack2.pop ()      for i iN post_expr:        if i.isdigit ():             stack1.push (i)          else:            op = i             top = stack1.pop ()              snext = stack1.pop ()              compute_exec (Op, int (Snext),  int (top))      return post_expr, stack1.pop () if __name__ ==  ' __main__ ':     stack1 = stacknode ()   #  operators     stack2 =  Stacknode ()   #  operand     exprs = [' ((4*2)-1) ',  ' ((3*4) + (3/2 )) ']    for e in exprs:        print e,  "==>",  Postfix (e)

Description

    1. The suffix expression means that the operator is after the operand.

    2. An expression is parsed from left to right. The value of the stack, encountered the symbol will be the top of the stack and the sub-position popup to calculate the [second bit operand stack top operand operator], the result is again into the stack until the expression parsing is complete

    3. The same is the [bitwise operand operation Fu Yi top operand] when evaluating the result of an expression


Iv. Summary

    1. All of the above examples can be viewed by http://pythontutor.com/visualize.html#mode=edit each step of the program running

    2. This article refers to Https://www.gitbook.com/book/facert/python-data-structure-cn/details

    3. The latter two sample codes are written based on their own understanding, and there may be bugs

    4. The disadvantage of the latter two examples is that there is no check for the legality of the write expression, the precedence of the expression (such as an expression without parentheses may cause a program exception)

    5. This is only a superficial understanding of the stack and its application.


This article is from the "gentle" blog, make sure to keep this source http://essun.blog.51cto.com/721033/1941041

Application of data structure [Python--stack]

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.