Python Data Structure-Implementation of stacks and queues (1)

Source: Internet
Author: User

1. Stack

Stack is a table that only supports insert and delete operations in one position. It is the end of the table and is called the top of the Stack ). The basic stack operations include PUSH (in stack) and POP (Out stack ). Stack is also called the LIFO (post-in-first-out) table.

Implementation of stack 1.1
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 check the symbols in the program

Program syntax errors are often caused by the absence of a symbol. Stack can be used to check whether symbols are paired. Create an empty stack. If the character is an open sign ('({['), push it to the stack. If the symbol is a closed symbol (')]}'), an error is returned when the stack is empty, corresponding to the '()}' error. Otherwise, stack pop will be performed. If the pop-up symbol is not the corresponding open symbol, an error will be reported, corresponding to the '(}' error. If the stack is empty at the end of the file, an error is returned, corresponding to the '({}' error.

 

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 in ')]}':            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 hexadecimal conversion

Convert decimal to binary: Convert decimal to binary until the quotient is 0. Start reading from the leftmost number, and then read the right number 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

Postfix: A stack is used. When a number is seen in the stack, an operator is used to play two elements popped up from the stack and the result is pushed into the stack.

(7 + 8)/(3 + 2) Write 7 8 + 3 2 +/

Images from Problem Solving with Algorithms and Data Structures:

Suffix-to-suffix conversion: When an operand is read, it is placed in the output. When you read the operator (+,-, *,/), if the stack is empty, it is pushed into the stack. Otherwise, the stack elements are displayed in the output until the elements with lower priority are found. Read '(', press it into the stack, read ')', pop up the stack element and send it to the output until '(' is found. At the end, the stack element pops up until the stack becomes empty.

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.pop()            stack.push(i)    while not stack.isEmpty():        post+=stack.pop()    return post                   def postfixExp(postfix):    stack=Stack()    postlist=postfix.split()    for i in postlist:        if i not in '+-*/':            stack.push(i)        else:            a=stack.pop()            b=stack.pop()            result=math(i,b,a)            stack.push(result)    return stack.pop()def math(x,y,z):    if x=='+':        return float(y)+float(z)    if x=='-':        return float(y)-float(z)    if x=='*':        return float(y)*float(z)    if x=='/':        return float(y)/float(z)
2 Queue

A queue is also a table. When a queue is used, it is inserted and deleted on different ends. The basic operation of the queue is Enqueue. insert an element at the end of the table (rear), and delete the elements starting with the table (Dequeue.

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)

  

  

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.