【发布时间】:2020-05-28 17:22:36
【问题描述】:
我正在 python 中实现 BFS。为了将图表的节点添加到队列中,我使用以下代码行:
graph = {}
graph['you'] = 'Alice','Bob','Claire'
search_queue+=graph['you']
这完美地将我的键值存储为队列中的单独元素。但是,如果我的密钥只有一个值,例如
graph['Alice'] = 'Peggy'
search_queue+=graph['Alice']
输出是一个队列,其中 'p'、'e'、'g'、'g'、'y' 存储为单独的值。我知道应该使用 append() 将元素添加到队列或列表中,但我需要为不同的键添加多个值和单个值。有没有办法以不同的方式做到这一点?到目前为止,我在graph['Alice'] = 'Peggy', 之类的值末尾使用了',' 来处理可以与队列或列表连接而不会丢失字符串的键值。但我确信一定有更好的方法。这是我的代码-
from collections import deque
def congratulations_msg():
'''message to display success'''
print('Congratulations, we have found the element')
graph = {}
graph['you'] = 'Alice','Bob','Claire',
graph['Bob'] = 'Anuj','Peggy',
graph['Claire'] = 'Johnny','Thom',
graph['Alice'] = 'Peggy',
graph['Peggy']='you',
# Assign element to be searched
seller='Thom'
#Create a dequeue to store nodes
search_queue = deque()
# Initialize queue with values of 'you' key
search_queue+=graph['you']
checked_elements=[]
# Loop while queue is not empty
while search_queue:
print(search_queue)
#Check if element in queue already processed
if search_queue[0] in checked_elements:
search_queue.popleft()
continue
#Check if queue element is the one that we are looking for
elif seller == search_queue[0]:
congratulations_msg()
break
else:
#Store store processed queue element and add its nodes to the queue
checked_elements+= search_queue[0],
popped_element = search_queue.popleft()
checked_elements+= popped_element
search_queue+=graph.get(popped_element,'')
【问题讨论】:
-
如果
graph应该是一个邻接列表,我认为你已经有了正确的方法。混合使用字符串和元组(都是可迭代对象)只会使您的代码复杂化。
标签: python algorithm queue breadth-first-search