Python data structure--stack, queue implementation (i)

Source: Internet
Author: User
1. Stack

A stack is a table that restricts insertions and deletions to only one location, which is the end of the table, called the top of the stack. The basic operation of the stack is push (into the stack) and pop (out of the stack). The stack is also known as the LIFO (back-in-first-out) table.

Implementation of the 1.1 stack

Class Stack (object):    def __init__ (self):        self.stack=[]    def isEmpty (self):        return self.stack==[]    def push (Self,item):        self.stack.append (item)    def pop (self):        if Self.isempty ():            raise Indexerror, ' Pop from empty stack '        return Self.stack.pop ()    def peek (self):        return self.stack[-1]    def size (self):        return len (self.stack)

1.2 Stack applications

1.2.1 Symbols in the check procedure

The syntax error of a program is often caused by the absence of a symbol. Use stacks to check if the symbols are paired. Make an empty stack, if the character is an open symbol (' ({[') then put it in the push stack. If the symbol is a closed symbol (')]} '), then the stack empty times is wrong, corresponding to the ' ()} ' error. Otherwise, the stack pops, if the pop-up symbol is not the corresponding open symbol, then error, corresponding ' (} ' errors. At the end of the file, if the stack is empty, an error occurs, corresponding to ' ({} ' errors.

def match (i,j):    opens= ' ([{'    closes= ')} '    return Opens.index (i) ==closes.index (j) def Syntaxchecker ( String):    stack=stack ()    balanced=true for    i in string:        if I in ' ([{':            stack.push (i)        elif i ') ]} ':            if Stack.isempty ():                balanced=false                break            else:                j=stack.pop ()                if not match (j,i):                    Balanced=false                    Break    if not Stack.isempty ():        balanced=false    return Balanced

1.2.2 Binary Conversion

Decimal conversion binary: Converts decimal into binary to be decomposed to a quotient of 0. Start reading from the bottom left number, then read the number on the right, and read from the bottom.

Images from problem solving with algorithms and Data structures:

Code:

def decimal_to_bin (dec):    stack=stack ()    Cur=dec while    cur>0:        a=cur%2        CUR=CUR/2        Stack.push (a)    binstr= "While not    Stack.isempty ():        binstr+=str (Stack.pop ())    return binstr


1.2.3 suffix notation

Suffix notation (postfix), using a stack, see a number of time into the stack, encountered an operator in the pop-up from the stack of two elements, the results bounce into the stack.

(7+8)/(3+2) can write 7 8 + 3 2 +/

Images from problem solving with algorithms and Data structures:

infix-to-suffix conversion: When a operand is read, it is placed in the output. When the operator (+,-, *,/) is read, the stack is pressed into the stack if it is empty, otherwise the pop-up stack element is placed in the output until a lower-priority element is found. Read ' (', press into the stack, read ') ', and pop the stack elements into the output until you find ' ('). At the end, the stack element pops up until the stack changes to an empty stack.

Images from problem solving with algorithms and Data structures:

def infixtopostfix (infix): a={} a[' * ']=3 a['/']=3 a[' + ']=2 a['-']=2 a[' (']=1 stack=stack () post= '        For i in Infix:if I not in A and i!= ') ': post+=i elif i== ' (': Stack.push (i) Elif i== ') ': Top=stack.pop () while top!= ' (': Post+=top top=stack.pop () Else:while not Stack.isempty () and A[i]<=a[stack.peek ()]: Post+=stack.po P () Stack.push (i) While not Stack.isempty (): Post+=stack.pop () return post Def P            Ostfixexp (postfix): Stack=stack () Postlist=postfix.split () for I in Postlist:if I is not in ' +-*/': Stack.push (i) Else:a=stack.pop () B=stack.pop () Result=math (i,b,a) s        Tack.push (Result) return Stack.pop () def math (x, Y, z): if x== ' + ': return float (y) +float (z) if x== '-': return float (y)-float (zIf x== ' * ': return float (y) *float (z) if x== '/': return float (y)/float (z) 

2 queues

Queues are also tables that are inserted and deleted at different ends when the queue is used. The basic operation of the queue is Enqueue (queued), inserting an element at the end of the table (rear), and a dequeue (Dequeue), deleting the element at the beginning of the table.

Class Queue (object):    def __init__ (self):        self.queue=[]    def isEmpty (self):        return self.queue==[]    def enqueue (self,x):        self.queue.append (x)    def dequeue (self):        if Self.queue:            a=self.queue[0]            Self.queue.remove (a)            return a        else:            raise Indexerror, ' queue is empty '    def size (self):        return Len (self.queue)

The above is the Python data structure-stack, queue implementation (a) of the content, more related articles please pay attention to topic.alibabacloud.com (www.php.cn)!

  • 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.