Implementation and application of [data structure] stack Python code example

Posted by broann on Thu, 10 Feb 2022 12:27:32 +0100

 

catalogue

The stack is implemented as follows:

Several practical applications of stack

The stack is implemented as follows:

Method 1: take the tail of the list as the top of the stack, and use the list method append and pop to realize the stack

class Stack:
    def __init__(self): #Initialization class
        self.items=[]
    def isEmpty(self):  #Judge whether the stack is empty and the return value is Boolean
        return self.items==[]
    def push(self,item):  #Adding an element to the top of the stack has no return value
        self.items.append(item)
    def pop(self):   #Pop up the stack top element, and the return value is the stack top element
        return self.items.pop()
    def peek(self):   #Get the top of the stack element, and the return value is the top of the stack element without changing the stack
        return self.items[len(self.items)-1]
    def size(self): #Get the quality of elements in the stack, and the return value is an integer
        return len(self.items)
s=Stack()
s.push('first')
s.push('second')
s.push('thirth')
print(s.isEmpty())
print(s.peek())
print(s.size())
l=s.size()
print('The pop-up sequence of stack elements is:')
for i in range(0,l):
    print(s.pop())


Method 2: take the head of the list as the top, and use pop and insert methods to realize stack operation

class Stack:
    def __init__(self):
        self.items=[]
    def isEmpty(self):
        return self.items==[]
    def push(self,item):
        self.items.insert(0,item)
    def pop(self):
        return self.items.pop()
    def peek(self):
        return self.items.pop(0)
    def size(self):
        return len(self.items)
s=Stack()
s.push('first')
s.push('second')
s.push('thirth')
print(s.isEmpty())
print(s.peek())
print(s.size())
l=s.size()
print('The pop-up sequence of stack elements is:')
for i in range(0,l):
    print(s.pop())

Several practical applications of stack

  • Match the parentheses. Let's talk about the basic idea of the algorithm: traverse a string from left to right, press the left parenthesis into the stack, pop up the stack with the right parenthesis, and finally judge the empty stack. If the stack is empty and the traversal is completed, it will return true, otherwise it will return False. The logic is relatively simple without comments. The code example is as follows:
from Class import  Stack
def kuohaopipei(strings):
    k=Stack()
    balanced=True
    index=0
    while index<len(strings) and balanced:
        flag=strings[index]
        if flag=='(':
            k.push(flag)
        else:
            if k.isEmpty():
                balanced=False
            else:
                k.pop()
        index+=1
    if balanced and k.isEmpty():
        return True
    else:
        return False
test='(((()()())))'
print(kuohaopipei(test))



  • Basic idea of matching symbol} algorithm: traverse a string from left to right, press the left bracket into the stack, pop up the stack with the right bracket, and finally judge the empty stack. If the stack is empty and the traversal is completed, it returns true, otherwise it returns False, which is basically the same as the previous bracket matching, However, because there are multiple symbols "{(["), a maches method is added to judge whether the left and right match. The index method is mainly used to judge whether the left and right match by returning the index position of the element. The code example is as follows:
from  Class import  Stack
def fuhaopipei(strings):
    ss=Stack()
    index=0
    balanced=True
    while index<len(strings) and balanced:
        flag=strings[index]
        if flag in "{[(":      #If there is a left symbol, it is pushed into the stack
            ss.push(flag)
        else:                  #If there is no left sign, judge whether the stack is empty first. If it is empty, it indicates that it does not match. If it is not empty, take the top element of the stack and the current traversal element to judge whether it matches
            if ss.isEmpty():
                balanced=False
            else:
                top=ss.pop()    #Get stack top element
                if not matches(top,flag):
                    balanced=False
        index+=1
    if balanced and ss.isEmpty():
        return True
    else:
        return False
def matches(open,close):      #Matching method
    opens="([{"
    closes=')]}'
    return  opens.index(open)==closes.index(close)  #The index() function is used to find the index position of the first match of a value from the list
test='{[()()]}'
print(fuhaopipei(test))


  • Basic idea of decimal conversion: use% remainder to press the obtained results into the stack in turn, and then take out the elements from the top of the stack in turn, which is the result of conversion from decimal to binary. The code example is as follows:
from Class import Stack
def devidedBy2(printnum):
    stack_1=Stack()
    while printnum>0:
        l=printnum%2
        stack_1.push(l)     #Push remainder onto stack
        printnum=printnum//2
    string=''              #Create a string
    while not stack_1.isEmpty():
        string=string+str(stack_1.pop()) #Taking out the corresponding elements from the top of the stack in turn is the result of binary conversion from decimal to binary
    return string   #str function is Python's built-in function, which converts parameters into string type, that is, a form suitable for human reading.
print(devidedBy2(568))
  • The basic idea of decimal conversion to arbitrary hexadecimal (highest hexadecimal): create a digital string to store the numbers in the corresponding position, and then take the corresponding numbers from the corresponding index when the output result is finally formed. The code is as follows:
    from Class import Stack
    def dividedBy2(printnum,base):
        zh_num='0123456789ABCDEF' #Create a string to store the number in the corresponding position
        stack_1 =Stack()
        while printnum>0:
            l=printnum%base
            stack_1.push(l)
            printnum=printnum//base
        string=''
        while not stack_1.isEmpty():
            string=string+zh_num[stack_1.pop()] #Find the number in the corresponding hexadecimal position through the index
        return string
    print(dividedBy2(59888,16))

    Operation results:

Topics: Python data structure stack