现在已经坚持这个问题很长一段时间了,是时候得到一些帮助了。几乎一切都有效。它读取文件并输入数据等等。程序不给我任何输出,最后的if语句有问题..最后三行是
root1.put(word1)
if root.exists(word1):
print(word1, end = " ")
它将值放入树中。然后,如果值“word1”已经在该树中,它将检查第一个树,如果这是真的,它将打印出该单词,如果不继续。这个程序只给我一个空输出。有人有机会看到这个问题吗?只有没有1到所有变量/ para ..
,其他类文件看起来几乎相同类文件(root1)
class BintreeEN:
def __init__(self, data1):
self.left1 = None
self.right1 = None
self.data1 = data1
def put(self, data1):
if data1 < self.data1:
if self.left1 is None:
self.left1 = BintreeEN(data1)
else:
self.left1.put(data1)
else:
if self.right1 is None:
self.right1 = BintreeEN(data1)
else:
self.right1.put(data1)
def write(self):
if self.left1:
self.left1.write()
print(self.data1)
if self.right1:
self.right1.write()
def exists(self, data1):
if data1 < self.data1:
if self.left1 is None:
return None, None
return self.left1.exists(data1)
elif data1 > self.data1:
if self.right1 is None:
return None, None
return self.right1.exists(data1)
else:
return self.data1
程序文件
#first tree
root = Bintree("root")
with open("word3.txt", "r", encoding = "utf-8") as file:
for row in file:
word = row.strip()
checklist = root.exists(word)
if checklist == word:
pass
else:
root.put(word)
#second tree
root1 = BintreeEN("root1")
with open('engelska.txt','r', encoding = "utf-8") as f:
for row in f:
onerow = row.split()
for rowz in onerow:
word1 = rowz.strip()
#HERE IT something thats wrong...
if root1.exists(word1):
pass
else:
root1.put(word1)
if root.exists(word1): #Check if value is in the first tree
print(word1, end = " ")
答案 0 :(得分:2)
您的exists()
方法返回True值,始终。永远不会调用.put()
,因为第一个if
始终为真:
if root1.exists(word1):
pass
如果树中不存在值,则.exists()
方法返回(None, None)
,而非空元组总是为真:
>>> if (None, None):
... print 'A tuple is considered True if not empty'
...
A tuple is considered True if not empty
返回只是 None
而不是元组:
def exists(self, data1):
if data1 < self.data1:
if self.left1 is None:
return None
return self.left1.exists(data1)
elif data1 > self.data1:
if self.right1 is None:
return None
return self.right1.exists(data1)
else:
return self.data1
或者,通过使用and
的短路性质以及return
立即退出该函数的事实:
def exists(self, data1):
if data1 < self.data1:
return self.left1 and self.left1.exists(data1)
if data1 > self.data1:
return self.right1 and self.right1.exists(data1)
return self.data1
通过此更改,您的二叉树可以正常工作:
>>> tree = BintreeEN('foo')
>>> tree.exists('foo')
'foo'
>>> tree.exists('bar')
>>> tree.put('bar')
>>> tree.exists('bar')
'bar'