Now on to the second half of the search process:
For each child of the current node Make a copy of the current path Add the child to the copy Append the updated path to the frontier
To ensure each child node has its own list, we need to make a copy of
current_path and append the child node. Making a copy of the list is important so each child node has its own list added to the frontier. If
current_path is not copied then the children will be added to the same list which will result in an incorrect path as well as only one child being searched.
Assigning a list to a new variable name does not make a copy of the original list. The new variable will still reference the same list. Python gives us multiple options to make a copy of a list each with its own reference:
original_list = ["My", "ideas", "are", "unique", "!"] copy_list1 = original_list[:] copy_list2 = original_list.copy() copy_list3 = list(original_list)
In the above example, the three copied lists can have elements added to them without affecting the original list.
In the example below we add an element to one of the copies. The output shows the copy is updated and the original list is unchanged.
copy_list1.append("See?") print(copy_list1) print(original_list) # Output # ["My", "ideas", "are", "unique", "!", "See?"] # ["My", "ideas", "are", "unique", "!"]
To create the paths for the frontier queue you now must loop through the
children list in
current_node and make a new path for each one.
- Create a
forloop with a loop variable called
childthat iterates through
- Inside the loop, define the variable
new_pathand set it to a copy of
Add the new path with the added child to the frontier queue to keep the search going.
for loop, do the following:
new_pathto the left side of
Test out the algorithm implementation by updating the goal value to initiate a deeper search.
- In main.py replace the second argument in the
bfs()call with the value
When you run the code you should now see a longer path output, which includes the root node value, the goal node value, and all values in between.