0

I am implementing BFS in python. In order to add nodes of my graph to my queue, I am using the following lines of code:

graph = {} graph['you'] = 'Alice','Bob','Claire' search_queue+=graph['you'] This perfectly stores my key values as separate elements in the queue. However, If my key has a single value, for eg graph['Alice'] = 'Peggy' search_queue+=graph['Alice'] The output is a queue with 'p','e','g','g','y' stored as separate values. I am aware that append() should be used to add an element to a queue or a list, but I need to add both multiple and single values for different keys. Is there a way to do this differently? So far, I have used ',' at the end of the value like graph['Alice'] = 'Peggy', to process key value that can be concatenated with a queue or a list without losing the string. But I am sure that there must be a better way. Here is my code-

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,'')
yash471994
  • 63
  • 7
  • If `graph` is supposed to be an adjacency list, I think you already have the right approach. Using a mix of strings and tuples (both iterables) will just complicate your code. – chash May 28 '20 at 18:09

1 Answers1

0

You could define a small function that handles enumerating the right values. Assuming the value elements are either a string or a list of strings

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

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

If you don't assume that the individual elements are string the solution could be more involved. You could use

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

to check if the value is a nested iterator. But at that point I'd seriously consider thinking closely if the types of the dict values can't be homogeneous.

kanales
  • 16
  • 3