一.问题定义
1.各参赛团队基本信息的存储管理,包括增删改各参赛队伍信息。
2.从txt文件读取各参赛队伍信息,根据赛事编号实现二叉排序树的查找。
二.问题分析
1.对于问题一,先从txt文档中读取所有团队信息,由此依次创建一个团队类,实现各参赛队伍信息的存储与管理;增添实例方法,实现对团队信息的增删改查操作。并将所有的团队类实例对象作为值,团队编号作为键存储到字典中,方便后续其他操作。
2.对于问题二,按行读取文档中所有团队信息,循环遍历每行也就是每队信息,去除\t,按#分割后,将编号信息存储到列表。为了实现利用二叉排序树实现按团队编号查找,创建一个二叉链表类和一个二叉排序树类。在二叉排序树中增添用来以团队编号大小创建二叉排序树的实例方法(团队编号列表作为形参)和以递归方式在二叉排序查找的实例方法,返回查找结果和ASL。如果查找成功,并调用团队类的打印信息函数,将查找到的相关团队信息打印出来。
三.代码部分实现
class TeamInfo:
def __init__(self, number, work, school, category, competitor, teacher):
self.number = number
self.work = work
self.school = school
self.category = category
self.competitor = competitor
self.teacher = teacher
def add_info(self,info_type,info):
pass
def delete_info(self):
pass
def change_info(self,info_type,info):
if info-type == "团队编号":
self.number = info
elif info_type == "参赛作品名称":
self.work = info
elif info-type == "参赛学校":
self.school = info
elif info-type == "参赛类别":
self.category = info
elif info-type == "参赛者":
self.competitor = info
else:
self.teacher = info
def print_info(self):
print("该团队参赛作品名称为{}".format(self.work))
print("参赛学校为{}".format(self.school))
print("参赛类别为{}".format(self.category))
print("参赛者为{}".format(self.competitor))
print("指导老师为{}".format(self.teacher))
class BiNode:
def __init__(self, key=None, lchild=None, rchild=None):
self.key = key
self.lchild = lchild
self.rchild = rchild
class BiSortTree:
def __init__(self, n):
self.root = None
self.count = 0
self.n = n
def create_bst(self,seq:list):
for i in range(self.n):
s = BiNode(key=int(seq[i]))
self.root = self.insert(self.root, s)
def insert(self,root:BiNode,s:BiNode)->BiNode:
if root:
if s.key < root.key:
root.lchild = self.insert(root.lchild, s)
else:
root.rchild = self.insert(root.rchild, s)
else:
return s
return root
def search(self,root:BiNode,k:int):
if root:
if root.key == k:
self.count += 1
self.count = round(self.count / self.n, 4)
return "查找成功", self.count
elif k < root.key:
self.count += 1
return self.search(root.lchild, k)
else:
self.count += 1
return self.search(root.rchild, k)
else:
return "查找失败", 0
def search_team():
with open("team", "r", encoding="utf-8") as file:
messages = file.readlines()
management = {}
for message in messages[1:]:
ateam = message.replace("\t", "").strip().split("#")
print(ateam)
management[ateam[0]] = TeamInfo(ateam[0], ateam[1], ateam[2], ateam[3], ateam[4], ateam[5])
numbers = list(management.keys())
a = BiSortTree(len(numbers))
a.create_bst(numbers)
num = input("请输入需要查询的团队编号:")
result, asl = a.search(a.root, int(num))
print(result, "ASL=", asl)
if result == "查找成功":
print(management[num].print_info())