这是一个学校项目。它是一个使用 BFS 返回从起始词到另一个结束词的最短路径的程序。我必须将起始单词与我拥有的单词列表进行交叉检查,并将该单词保存在名为 children 的列表中。我想在运行程序时打印列表 Children。为什么我在运行程序时看不到 Children 列表?
import bintree
import imp
imp.reload(bintree)
from queuelist import Queue
class Word:
def __init__(self, w, f = None):
self.word = w
self.parent = f
filename = 'word3u'
fin=open(filename,'r')
tree = bintree.Bintree()
alist = fin.readlines()
lista='abcdefghijklmnopqrstuvwxyz'
doubles=bintree.Bintree()
for ord in alist:
word=ord.strip()
tree.put(word)
def generator(parent):
children=[]
theWord=parent.word
doubles.put(theWord)
#print(theWord)
n=0
while n<3:
for i in lista:
if n==0:
theWord=i+theWord[1:]
#print("1 "+theWord)
if n==1:
theWord=theWord[0]+i+theWord[2]
#print("2 "+theWord)
if n==2:
theWord=theWord[0:2]+i
#print("3 "+theWord)
if tree.exists(theWord):
#print("THIS " + theWord)
if not doubles.exists(theWord):
#print("THIS 2 " + theWord)
children.append(Word(theWord, parent))
doubles.put(theWord)
theWord=parent.word #reset theWord for next n
n+=1
return children
generator(Word("fan"))
请您参考如下方法:
由于您在函数中返回了 childeren,因此您需要在调用它时打印您的对象。因此只需执行以下操作:
print(generator(Word("fan")))
