【问题标题】:Adding multiple key values to a queue for BFS in python在python中为BFS的队列添加多个键值
【发布时间】: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


【解决方案1】:

您可以定义一个处理枚举正确值的小函数。假设值元素是字符串或字符串列表

def get_values(element):
    if isinstance(element, str):
        # its a string
        return element,
    return element

# usage
search_queue += get_values(graph['alice'])

如果您不假设单个元素是字符串,则解决方案可能会涉及更多。你可以使用

>>> from collections.abc import Iterator
>>> isinstance('abc', Iterator)
False
>>> isinstance(('abc',), Iterator)
True

检查该值是否为嵌套迭代器。但在这一点上,如果 dict 值的类型不能是同质的,我会认真考虑仔细考虑。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-17
    • 2019-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多