#3.10.1
from pythonds.basic import Stack
import string
def infixToPostfix(infixexpr):
prec = {}
prec["*"] = 3
prec["/"] = 3
prec["+"] = 2
prec["-"] = 2
prec["("] = 1
opStack = Stack()#创建空栈
postfixList = [] #存储输出结果
tokenList = [_ for _ in infixexpr]#将输入字符串转化为数组
count = 0
for token in tokenList:
if count <= len(tokenList) - 2:
if token in prec.keys() and tokenList[count+1] in prec.keys():
print("输入运算符号错误")
return
if token in string.ascii_uppercase:
postfixList.append(token)
elif token not in prec.keys():
print("输入错误")
return
elif token == "(":
opStack.push(token)
elif token == ")":
topToken = opStack.pop()
while topToken != ")":
postfixList.append(token)
topToken = opStack.pop()
else:
while not opStack.isEmpty() and prec[opStack.peek()] >= prec[token]:
topToken = opStack.pop()
postfixList.append(topToken)
opStack.push(token)
count += 1
while not opStack.isEmpty():
postfixList.append(opStack.pop())
return "".join(postfixList)
print(infixToPostfix("A+*C+B+C*D"))
#3.10.10
"""
基数排序器
1个主桶
10个数位桶
每个水桶是一个数列 按照先后顺序维持这些值
步骤:
1、先将所有数字放到主桶中
2、按考察的数位将其放到对应的数位桶中
3、依次从0-9号数位桶中将值放回主桶
重复上述过程,知道最后一个数位被处理完
分析:
1、首先,最大数 的位数 确定要排序多少次
2、获取每个数字的个位 十位 用取余
3、主桶用一个队列去实现 从头插入 从尾部取出
4、数位桶用 对列实现 先进先出
"""
"""
123 325 265 458 951 657 257 852
0:
1: 951
2: 852
3: 123
4:
5:325 265
6:
7:657 257
8:458
9:
951 852 123 325 256 657 257 458
0:
1:
2: 123 325
3:
4:
5:951 852 256 657 257 458
6:
7:
8:
9:
123 325 951 256 657 257 458
0:
1: 123
2: 256 257
3: 325
4:458
5:
6:657
7:
8:
9:951
123 256 257 325 458 657 951
"""
from pythonds.basic import Queue
def sortNum(mainbarrel,le):
subbarrel = [Queue() for _ in range(10)]#创建10个子桶
while not mainbarrel.isEmpty():
num = mainbarrel.dequeue()#取出一个元素
#去判断它的某一位是否
index = num // pow(10,le) % 10
subbarrel[index].enqueue(num)
for i in subbarrel:
while not i.isEmpty():
mainbarrel.enqueue(i.dequeue())
return mainbarrel
mainbarrel = Queue()
x = [123,456,741,596,235,124,526,125,459,789,963,212,525,636]
for i in x:
mainbarrel.enqueue(i)
for i in range(3):
mainbarrel = sortNum(mainbarrel,i)
while not mainbarrel.isEmpty():
print(mainbarrel.dequeue())