我成功创建了一个BST,它从文本文件中读取数据并相应地连接节点,虽然是以不平衡的方式,但是,现在我遇到了用户输入问题。
以下是文本文件中的一行示例:
student id1, mark1, mark2, mark3, mark4, mark5, midterm mark, exam mark
将此功能转换为BST的功能如下所示:
def marks(tree, Data):
global assignment1
global assignment2
global assignment3
global assignment4
global assignment5
global midterm
global exam
global counter
for students in Data[:len(Data)-2]:
data = students.split(',')
assignment1 += float(data[1])
assignment2 += float(data[2])
assignment3 += float(data[3])
assignment4 += float(data[4])
assignment5 += float(data[5])
midterm += float(data[6])
exam += float(data[7])
if float(data[7]) < 32.5:
counter+=1
tree = add(tree, data)
return tree
def add(tree, data):
if tree == None:
tree = {'data':data,'left':None, 'right':None}
return tree
elif data[0] < tree['data'][0]:
tree['left'] = add(tree['left'], data)
return tree
elif data[0] > tree['data'][0]:
tree['right'] = add(tree['right'], data)
return tree
这会产生一个BST,但现在我想创建一个允许手动添加到BST的功能(总是在叶子上添加)。
def manual_addition(myTree):
new_student = {}
student_id = input("Please enter the student id: ")
hw1 = input("Please enter their first assignment mark: ")
hw2 = input("Please enter their second assignment mark: ")
hw3 = input("Please enter their third assignment mark: ")
hw4 = input("Please enter their fourth assignment mark: ")
hw5 = input("Please enter their fifth assignment mark: ")
midterm = input("Please enter their midterm mark: ")
exam = input("Please enter their final exam mark: ")
new_student = [student_id, hw1, hw2, hw3, hw4, hw5, midterm, exam]
myTree = add(myTree, new_student)
return myTree
然而,当我打印我的BST时,例如我输入的ID是300,它出现在id大于2000的右边。它应该出现在我的BST的最左边,因为它的最低id文本文件是2000.我的错误是什么?
答案 0 :(得分:0)
事实证明,我忘记做的就是提到数据类型是浮点数,这让我感到困惑,因为我想知道当比较运算符比较字符串时,如何在第一个位置创建二叉搜索树。 / p>