[Abstract data type of stack] Python implementation of ADT stack

Stack abstract data type

  • Stack Stack: What is a stack?
    • An ordered collection of data items in which items are added and removed only at the same end of the stack
    • The closer the data item is to the bottom of the stack, the longer it stays in the stack, and the newly added data item will be removed first. That is, LIFO: Last In First Out
  • The characteristics of the stack: order reversal

Stack operations and operation examples

  • stack operations
    insert image description here
  • Stack operation example
    insert image description here

Python implementation

  • the end of the list as the top of the stack
class Stack:
	def __init__(self):
		self.items = []
	def isEmpty(self):
		return self.items == []
	def push(self, item):
		self.items.append(item)
	def pop(self):
		return self.items.pop()
	def peek(self):
		return self.items[len(self.items)-1]
	def size(self):
		return len(self.items)
  • The head of the list is treated as the top of the stack
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(0)
	def peek(self):
		return self.items[0]
	def size(self):
		return len(self.items)

Application of the stack: simple bracket matching

  • It is very common to add parentheses in the calculation, but the parentheses are not added casually, and the parentheses need to be matched. For example, "(( ))" is in compliance with the rules, but "((( ))" is not in compliance with the rules.
def JudgeBalance(s):
    stack = []
    for i in s:
        if i == "(":
            stack.append(i)
        elif i == ")":
            if len(stack) == 0:
                return False
            else:
                stack.pop()
    if len(stack) == 0:
        return True
    else:
        return False
  • Include "[]" and "{}" in brackets. Those that meet the rules are "{[()]}", and those that do not, such as "{([ }])"
def JudgeBalance(s):
    matchs = {
    
    '{':'}', '[':']', '(':')'}
    stack = []
    for i in s:
        if i in "([{":
            stack.append(i)
        elif i in ")]}":
            if len(stack) == 0:
                return False
            else:
                top = stack.pop()
                if matchs[top] != i:
                    return False
                
    if len(stack) == 0:
        return True
    else:
        return False

Stack application: base conversion

  • Convert decimal to binary
def divideBy2(number):
	if number == 0:
		return '0'
	res = []
	while number > 0:
		res.append(number % 2)
		number //= 2
	binString = ""
	while len(res) != 0:
		binString = binString + str(res.pop())
	return binString	
  • Convert decimal to other bases
def divideBy2(number, base):
	if number == 0:
		return '0'
	digits = "0123456789ABCDEF"
	res = []
	while number > 0:
		res.append(number % base)
		number //= base
	binString = ""
	while len(res) != 0:
		binString = binString + digits[res.pop()]
	return binString

Application of the stack: converting infix expressions to postfix expressions

def infixToPostfix(infixexpr):
    """
    :infixexpr: 中缀表达式字符串,以空格隔开
    :return: 后缀表达式,以空格隔开
    """
    # 记录操作符优先级
    prec = {
    
    }
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec["("] = 1
    opStack = []
    postfixList = []
    tockenlist = infixexpr.split()

    for token in tockenlist:
        if token in "ABCDEFGHIJKLMNOPQRSTUVWSYZ" or token in "0123456789":
            postfixList.append(token)
        elif token == "(":
            opStack.append(token)
        elif token == ")":
            topToken = opStack.pop()
            while topToken != "(":
                postfixList.append(topToken)
                topToken = opStack.pop()
        else:
            while (len(opStack) != 0) and (prec[opStack[-1]] >= prec[token]):
                postfixList.append(opStack.pop())
            opStack.append(token)
    while len(opStack) != 0:
        postfixList.append(opStack.pop())
    return " ".join(postfixList)

Reference video material: Application of stack: convert infix expression to suffix expression
Reference video material: stack abstract data type and python implementation

Guess you like

Origin blog.csdn.net/qq_38734327/article/details/132308960