[英]check existing values in binary tree python
Have some errors and been stuck on this problem for awhile. 有一些错误,并在此问题上停留了一段时间。 I read words from a file like this below but the problem is with the if statements.
我从下面的文件中读取单词,但是问题出在if语句上。 it doesn't print an existing value it just keeps printing all values to the screen.
它不打印现有值,而是一直将所有值打印到屏幕上。 I am using python 3.3.. If you check the file the only value it would print is via and not add it again to the tree.
我正在使用python 3.3 ..如果您检查文件,则它将打印的唯一值是通过,而不是再次将其添加到树中。
Textfile - words.txt
words.txt
nia
ria
via
sia
via
Code 码
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")
I would remove the "self" keyword in the invocation of the exists method. 我将在存在方法的调用中删除“ self”关键字。 When calling a method we do not have to specify the "self" keyword.
调用方法时,我们不必指定“ self”关键字。
So, instead of: 因此,代替:
return self.left.exists(data, self)
return self.right.exists(data, self)
I would simply use: 我只会使用:
return self.left.exists(data)
return self.right.exists(data)
When passing self to the method, you should actually get a traceback complaining that you are passing an extra argument to exists() method. 当将self传递给该方法时,您实际上应该得到一个回溯,抱怨您要将一个额外的参数传递给exist()方法。 I quickly tried running your code and got a traceback like this:
我迅速尝试运行您的代码,并得到如下所示的回溯:
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)
How about this: 这个怎么样:
....
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.