有一些错误并且在这个问题上停留了一段时间。我从下面这样的文件中读取了单词,但问题出在 if 语句上。它不打印现有值,它只是将所有值打印到屏幕上。我正在使用 python 3.3 .. 如果您检查文件,它将打印的唯一值是 via,而不是将其再次添加到树中。
文本文件 -words.txt
nia
ria
via
sia
via
代码
class Bintree:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def put(self, data):
if data < self.data:
if self.left is None:
self.left = Bintree(data)
else:
self.left.put(data)
else:
if self.right is None:
self.right = Bintree(data)
else:
self.right.put(data)
def write(self):
if self.left:
self.left.write()
print(self.data)
if self.right:
self.right.write()
def exists(self, data):
if data < self.data:
if self.left is None:
return None, None
return self.left.exists(data, self)
elif data > self.data:
if self.right is None:
return None, None
return self.right.exists(data, self)
else:
return self.data
root = Bintree("root")
with open("words.txt", "r", encoding = "utf-8") as file:
for row in file:
word = row.strip()
checklist = root.exists(word)
if checklist == word:
print(word, end = " ")
else:
root.put(word)
print("\n")