栈的抽象数据类型
Stack()创建一个空栈。它不需要参数,且会返回一个空栈。
push(item)将一个元素添加到栈的顶端。它需要一个参数item,且无返回值
pop()将栈顶端的元素删除。它不需要参数,但会返回顶端的元素,并且修改栈的内容
peek()返回栈顶端的元素,但是不移除该元素。它不需要参数,也不会修改栈的内容。
is_empty()检查栈是否为空。它不需要参数,且会返回一个布尔值。
size()返回栈中元素的数目。它不需要参数,且会返回一个整数。
class MyStack(object):
def __init__(self):
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 is_empty(self):
return self.items == []
def size(self):
return len(self.items)
括号匹配问题
def par_checker(string):
s = MyStack()
l = len(string)
i = 0
while i < l:
if string[i] == '(':
s.push(')')
elif string[i] == '[':
s.push(']')
elif string[i] == '{':
s.push('}')
else:
pass
if string[i] == ')' or string[i] == ']' or string[i] == '}':
if s.is_empty():
return False
if s.pop() != string[i]:
return False
i += 1
if s.is_empty():
return True
return False
十进制转二进制
此处不会讲解十进制转二进制的思想。如果有同学对这方面的知识不懂,可以百度了解。
def divide_by2(dec_number):
s = MyStack()
while dec_number > 0:
s.push(dec_number % 2)
dec_number = dec_number // 2
bin_string = ""
while not s.is_empty():
bin_string = bin_string + str(s.pop())
return bin_string
中序表达式转后缀表达式❗❗❗
def infix_to_postfix(infix_expr):
# 设置加减乘除的优先级
opt_priority = {
'+': 0,
'-': 0,
'*': 1,
'/': 1,
'(': -100
}
postfix = ""
opt_stack = MyStack()
str_len = len(infix_expr)
i = 0
while i < str_len:
if infix_expr[i] == ' ':
i += 1
continue
if infix_expr[i] == '(':
opt_stack.push('(')
i += 1
continue
if infix_expr[i] == ')':
pop_item = opt_stack.pop()
while pop_item != '(':
postfix += pop_item
pop_item = opt_stack.pop()
i += 1
continue
# 操作数压入栈中
if infix_expr[i] == '+' or infix_expr[i] == '-' or infix_expr[i] == '*' or infix_expr[i] == '/':
if opt_stack.is_empty():
opt_stack.push(infix_expr[i])
else:
while (not opt_stack.is_empty()) and opt_priority.get(opt_stack.peek()) >= opt_priority.get(infix_expr[i]):
postfix += opt_stack.pop()
opt_stack.push(infix_expr[i])
# 普通的数直接写入后缀表达式
if infix_expr[i] != '+' and infix_expr[i] != '-' and infix_expr[i] != '*' and infix_expr[i] != '/':
postfix += infix_expr[i]
i += 1
while not opt_stack.is_empty():
postfix += opt_stack.pop()
return postfix
后缀表达式运算❗❗❗
-
创建空栈operandStack
-
使用字符串方法split将输入的后续表达式转换成一个列表
-
从左往右扫描这个标记列表
-
如果标记是操作数,将其换成整数并且压入operandStack栈中
-
如果标记是运算符,从operandStack栈中取出两个操作数。第一次取出右操作数,第二次取出左操作数。进行相应的算术运算,然后将运算结果压入operandStack栈中。
def postfix_eval(postfix_expr):
operand_stack = MyStack()
token_list = postfix_expr.split()
for token in token_list:
if token.isdigit():
operand_stack.push(float(token))
else:
operand2 = operand_stack.pop()
operand1 = operand_stack.pop()
result = do_math(token, operand1, operand2)
operand_stack.push(result)
return operand_stack.pop()
def do_math(op, op1, op2):
if op == '+':
return op1 + op2
elif op == '-':
return op1 - op2
elif op == '*':
return op1 * op2
else:
return op1 / op2