1 Star 0 Fork 0

K-on/data_structure

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
栈.py 2.96 KB
一键复制 编辑 原始数据 按行查看 历史
HASEE 提交于 2020-08-16 15:04 . 数据结构
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)
"""
括号匹配
"""
def matches(open, close):
opens = "{[("
closes = "}])"
return opens.index(open) == closes.index(close)
def check(strings):
s = Stack()
index = 0
while index < len(strings):
a = strings[index]
if a in "{[(":
s.push(a)
else:
if s.isEmpty():
return False
else:
top = s.pop()
if not matches(top, a):
return False
index += 1
if s.isEmpty():
return True
else:
return False
"""
进制转换
"""
def translate1(num):
s = Stack()
while num > 0:
a = num % 2 # 取余
s.push(a)
num = num // 2 # 整除
string = ""
while not s.isEmpty():
string = string + str(s.pop())
return string
def translate2(num, n): # 转n进制
s = Stack()
while num > 0:
a = num % n # 取余
s.push(a)
num = num // n # 整除
string = ""
while not s.isEmpty():
string = string + str(s.pop())
return string
"""
中缀表达式 传 前缀表达式
"""
def infix1(infixexpr):
# 记录操作符的优先级
prec = {}
prec["*"] = 3
prec["/"] = 3
prec['+'] = 2
prec['-'] = 2
prec["("] = 1
opstack = Stack()
lists = []
tokenlist = infixexpr.split() # 解析表达式到的单词列表
for token in tokenlist:
if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789":
lists.append(token)
elif token == "(":
opstack.push(token)
elif token == ')':
top = opstack.pop()
while top != '(':
lists.append(top)
top = opstack.pop()
else:
while(not opstack.isEmpty()) and (prec[opstack.peek()] >= prec[token]):
lists.append((opstack.pop()))
opstack.push(token)
while not opstack.isEmpty():
lists.append(opstack.pop())
print(''.join(lists))
return ''.join(lists)
"""
后缀表达式求值
"""
def domath(a, t1, t2):
if a == "*":
return t1 * t2
elif a == '/':
return t1 * t2
elif a == "+":
return t1 + t2
else:
return t1 - t2
def infix2(infixexpr):
opstack = Stack()
tokenlist = infixexpr.split() # 解析表达式到的单词列表
for token in tokenlist:
if token in "0123456789":
opstack.push(int(token))
else:
t1 = opstack.pop()
t2 = opstack.pop()
res = domath(token, t1, t2)
opstack.push(res)
return opstack.pop()
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/HuangJiaLuo/data_structure.git
[email protected]:HuangJiaLuo/data_structure.git
HuangJiaLuo
data_structure
data_structure
master

搜索帮助