有一些错误,并且暂时停留在这个问题上。我从下面这样的文件中读取了单词,但问题在于if语句。它不打印现有值,只是将所有值都打印到屏幕上。我正在使用python 3.3 ..如果你检查文件,它将打印的唯一值是通过,而不是再次添加到树。
文本文件 - 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")
答案 0 :(得分:0)
我会在调用exists方法时删除“self”关键字。在调用方法时,我们不必指定“self”关键字。
所以,而不是:
return self.left.exists(data, self)
return self.right.exists(data, self)
我只想使用:
return self.left.exists(data)
return self.right.exists(data)
当将self传递给方法时,实际上应该得到一个回溯,抱怨你正在向exists()方法传递一个额外的参数。我很快就尝试运行你的代码并获得了这样的追溯:
Traceback (most recent call last):
File "t.py", line 44, in <module>
checklist = root.exists(word)
File "t.py", line 30, in exists
return self.left.exists(data, self)
TypeError: exists() takes exactly 2 arguments (3 given)
答案 1 :(得分:0)
这个怎么样:
....
with open("words.txt","r",encoding="utf-8") as file:
a=file.readlines() # this reads the entire file as a list. Each line is an item in the list.
b=[i.strip('\n') for i in a] # this will get rid of newline characters '\n' in each item of the list
m=max([b.count(i) for i in b]) # this line will get you the highest number of occurrences of a word in your list
c=set([i for i in b if b.count(i)==1]) # this line will give you all words that occur m times
print(c)