1

有一些错误并且在这个问题上停留了一段时间。我从下面这样的文件中读取了单词,但问题出在 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")
4

2 回答 2

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)
于 2013-09-22T14:25:53.817 回答
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)
于 2013-09-22T14:57:10.227 回答