I Need some help here

Lets say I have this:

list_a = [cheese]

list_b = [hamburgers, hotdogs]

list_a = list_b.pop(0)

What will be the final result of list_a?

Guess: list_a = [cheese, hamburgers]

First off, you need quotes around your string values:list_a = ['cheese']
Second, your guess is incorrect. list_a = list_b.pop(0) will assign the value of the expression on the right side of = to the list on the left side of = replacing whatever value was previously assigned. Your output will be: list_a = ['hamburgers']
To get the output you guessed, you would have to append the value returned by list_b.pop(0) to list_a.


Hope this helps!

1 Like
def bfs(graph, start_vertex, target_value):
  path = [start_vertex]
  vertex_and_path = [start_vertex, path]
  bfs_queue = [vertex_and_path]
  visited = set()
  while bfs_queue:
    current_vertex, path = bfs_queue.pop(0)
    print("current_vertex = {0}, path = {1}".format(current_vertex, path))
    for neighbor in graph[current_vertex]:
      if neighbor not in visited:
        if neighbor is target_value:
          return path + [neighbor]
          bfs_queue.append([neighbor, path + [neighbor]])


`some_important_graph = 
    'lava': set(['sharks', 'piranhas']),
    'sharks': set(['lava', 'bees', 'lasers']),
    'piranhas': set(['lava', 'crocodiles']),
    'bees': set(['sharks']),
    'lasers': set(['sharks', 'crocodiles']),
    'crocodiles': set(['piranhas', 'lasers'])`

bfs(some_important_graph, 'lava', 'lasers')

Ok, so if you look at the line just before the print statement, current_vertex, path = bfs_queue.pop(0), the output of this is: current_vertex = lava, path = ['lava']

Why are current_vertex and path not equal to the exact same thing?

1. def bfs(graph, start_vertex, target_value):
2.   path = [start_vertex]
3.   vertex_and_path = [start_vertex, path]
4.   bfs_queue = [vertex_and_path]
5.   visited = set()
6.   while bfs_queue:
7.     current_vertex, path = bfs_queue.pop(0)

start_vertex is ‘lava’:

Keep track of brackets:

  • After line 2, path is [‘lava’] (start_vertex as the element in a list of len = 1)
  • So line 3 sets vertex_and_path to [start_vertex, path], which is now [‘lava’, [‘lava’]]
  • And line 4 sets bfs_queue to [vertex_and_path], which is [ [‘lava’, [‘lava’]]]
  • Then in line 7, in the tuple assignment, current_vertex, path = bfs_queue.pop(0), bfs_queue.pop(0) is [‘lava’, [‘lava’]], so current_vertex is ‘lava’, and path is [‘lava’].

When you print ‘lava’, you see lava on the screen
When you print [‘lava’], you see [‘lava’] on the screen