Algorithm 宽度优先算法的实现
我试图实现一个“广度优先”算法,作为我在一本书中看到的东西的一个变体 我的问题是算法没有将每个节点的元素添加到队列中 例如,如果我在“search()”函数中搜索名为“mariela”的“black lab”,我将得到正确的输出:“simon是一个black lab” 然而,我应该能够在“沃尔特”中找到“黑色实验室”,它与“玛丽拉”相连,玛丽拉与“西蒙”相连,西蒙是一个“黑色实验室”。这是行不通的 我是否在实现这个算法时犯了新手错误,或者我的图形设置错误 一如既往,我们非常感谢您的任何帮助Algorithm 宽度优先算法的实现,algorithm,breadth-first-search,Algorithm,Breadth First Search,我试图实现一个“广度优先”算法,作为我在一本书中看到的东西的一个变体 我的问题是算法没有将每个节点的元素添加到队列中 例如,如果我在“search()”函数中搜索名为“mariela”的“black lab”,我将得到正确的输出:“simon是一个black lab” 然而,我应该能够在“沃尔特”中找到“黑色实验室”,它与“玛丽拉”相连,玛丽拉与“西蒙”相连,西蒙是一个“黑色实验室”。这是行不通的 我是否在实现这个算法时犯了新手错误,或者我的图形设置错误 一如既往,我们非常感谢您的任何帮助 fr
from collections import deque
# TEST GRAPH -------------
graph = {}
graph['walter'] = ['luci', 'kaiser', 'andrea', 'mariela']
graph['andrea'] = ['echo', 'dante', 'walter', 'mariela']
graph['mariela'] = ['ginger', 'simon', 'walter', 'andrea']
graph['kaiser'] = 'german shepherd'
graph['luci'] = 'black cat'
graph['echo'] = 'pitbull'
graph['dante'] = 'pitbull'
graph['ginger'] = 'orange cat'
graph['simon'] = 'black lab'
def condition_met(name):
if graph[name] == 'black lab':
return name
def search(name):
search_queue = deque()
search_queue += graph[name] # add all elements of "name" to queue
searchedAlready = [] # holding array for people already searched through
while search_queue: # while queue not empty...
person = search_queue.popleft() # pull 1st person from queue
if person not in searchedAlready: # if person hasn't been searched through yet...
if condition_met(person):
print person + ' is a black labrador'
return True
else:
search_queue += graph[person]
searchedAlready.append(person)
return False
search('walter')
#search('mariela')
在您的实现中有很多问题,包括Python和算法方面的问题 重写为:
# @param graph graph to search
# @param start the node to start at
# @param value the value to search for
def search(graph, start, value):
explored = []
queue = [start]
while len(queue) > 0:
# next node to explore
node = queue.pop()
# only explore if not already explored
if node not in explored:
# node found, search complete
if node == value:
return True
# add children of node to queue
else:
explored.append(node)
queue.extend(graph[node]) # extend is faster than concat (+=)
return False
graph = {}
graph['walter'] = ['luci', 'kaiser', 'andrea', 'mariela']
graph['andrea'] = ['echo', 'dante', 'walter', 'mariela']
graph['mariela'] = ['ginger', 'simon', 'walter', 'andrea']
# children should be a list
graph['kaiser'] = ['german shepherd']
graph['luci'] = ['black cat']
graph['echo'] = ['pitbull']
graph['dante'] = ['pitbull']
graph['ginger'] = ['orange cat']
graph['simon'] = ['black lab']
print search(graph, 'mariela', 'walter')
这是一个演示谢谢。我来试一试。我已经用--print search(图形“沃尔特”、“德国牧羊犬”)运行了你的代码--它没有返回正确的输出。我收到了一个错误。原因是没有名为“pitbull”的节点,即使您有名为
pitbull
的子节点,您的图形中也没有名为“pitbull”的节点a)图形['pitbull']=[]
或B)更改此行队列。扩展(图形[节点])
toqueue.extend(graph.get(node,[]))