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,'')