我不想发布太多代码,但我已经完成了一项任务的代码,我的代码的问题是每次我运行一个名为findchildren
的方法时,它每次都会导入我的列表。所以我试着更改我的代码,我的findchildren
正在工作,它现在看起来是这样的:
from queue import Queue
ordlista=[]
fil=open("labb9text.txt")
for line in fil.readlines():
ordlista.append(line.strip())
setlista=set()
for a in ordlista:
if a not in setlista:
setlista.add(a)
def findchildren(lista,parent):
children=[]
lparent=list(parent)
lista.remove(parent)
for word in lista:
letters=list(word)
count=0
i=0
for a in letters:
if a==lparent[i]:
count+=1
i+=1
else:
i+=1
if count==2:
if word not in children:
children.append(word)
if i>2:
break
return children
我的问题是,我有另一个方法,当我在findchildren
中没有参数lista
时,它就起作用了(相反,我一遍又一遍地导入列表,我不想这样做,我想一开始就导入一次)。请注意,当我调用我的方法时,我使用labb9.findchildren(labb9.ordlista,"fan")
来调用它。所以我的findchildren
目前正在工作,问题是下面的方法:
def way(start,end):
queue=Queue()
queue.enqueue(start)
visited=set()
while not queue.isempty():
vertex=queue.get()
if vertex==end:
return True
else:
visited.add(vertex)
s=findchildren(labb999.ordlista,start)
for vertex in s:
if vertex not in visited:
queue.put(vertex)
else:
visited.add(vertex)
return False
请注意,每次将列表导入findchildren
时,way
-方法都会起作用,现在我已将其更改为findchildren
中的参数,它不起作用。我得到错误:
名称"lista"未定义。
我做错了什么?
您的目标是找出是否存在从start
到stop
的路径,其中路径被描述为长度为两个排列重叠的单词。
我认为你的代码最好组织成一个图和一个在这个图上操作的函数。它将消除您的所有问题:您可以将单词集的单个副本与图形对象关联,并可以使用函数way
直接对该对象进行操作。
from queue import Queue
import itertools
class Graph(object):
def __init__(self, filename):
# Creates a set, which removes duplicates automatically
self.word_set = {word for word in open(filename, 'r').read().split()}
def _len_2_permutations(self, word):
# Create a list of length two permutations from a word
return itertools.permutations(word, 2)
def has_word_overlap(self, word1, word2):
# If there are any overlapping length two permutations, the set will not be empty
return len(set(self._len_2_permutations(word1)) & set(self._len_2_permutations(word2))) > 0
def find_children(self, start):
# Children are those words who have overlapping length two perms
return [word for word in self.word_set if self.has_word_overlap(start, word) and word != start]
现在我们可以定义类似BFS的函数:
def way(g, start, stop):
queue = Queue()
# Push start
queue.put(start)
visited = set()
while not queue.empty():
# Get the top of the queue
vertex = queue.get()
# If it's our target, we're done
if vertex == stop:
return True
# Otherwise, visit it
visited.add(vertex)
# Find its children
s = g.find_children(vertex)
# Push the unvisited children -- explore them later
for vertex in s:
if vertex not in visited:
queue.put(vertex)
return False
现在让我们创建一个主:
if __name__ == "__main__":
g = Graph("foo.txt")
start = "fan"
stop = "foo"
print("There's a path from '{0}' to '{1}': {2}".format(start, stop, way(g, start, stop)))
这段代码没有经过彻底的测试,但它应该会让你走上正轨。