November 19, 2019
For today
Work on Notebook 11 (due next Friday)
Work on your project.
Today
Bayesian workshop
For next time:
Turn in Notebook 11
Work on your project
To get the notebooks, you can either
1) Clone/download them from the Bayes Made Simple repository.
2) Follow the links below to run the notebooks on Colab.
What is the order of growth of the following functions in terms of number of nodes, n, number of edges, m, and/or average degree, k?
Hint: not everything inside the loop runs the same number of times.
from collections import deque
def reachable_nodes_bfs(G, start):
seen = set()
queue = deque([start])
while queue:
node = queue.popleft()
if node not in seen:
seen.add(node)
queue.extend(G.neighbors(node))
return seen
def bfs(graph, start):
visited, queue = set(), [start]
while queue:
vertex = queue.pop(0)
if vertex not in visited:
visited.add(vertex)
queue.extend(graph[vertex] - visited)
return visited
Notice that this version avoids adding nodes to the queue more than once. Do you think that's likely to make the program faster, either by changing the order of growth or reducing overhead?
# visits all the nodes of a graph using BFS
def bfs_connected_component(graph, start):
# keep track of all visited nodes
explored = []
# keep track of nodes to be checked
queue = [start]
# keep looping until there are nodes still to be checked
while queue:
# pop shallowest node (first node) from queue
node = queue.pop(0)
if node not in explored:
# add node to list of checked nodes
explored.append(node)
neighbours = graph[node]
# add neighbours of node to queue
for neighbour in neighbours:
queue.append(neighbour)
return explored
def bfs(graph, root):
visited, queue = [], [root]
while queue:
vertex = queue.pop(0)
for w in graph[vertex]:
if w not in visited:
visited.append(w)
queue.append(w)
def BFS(self, s):
# Mark all the vertices as not visited
visited = [False]*(len(self.graph))
# Create a queue for BFS
queue = []
# Mark the source node as visited and enqueue it
queue.append(s)
visited[s] = True
while queue:
# Dequeue a vertex from queue and print it
s = queue.pop(0)
print s,
# Get all adjacent vertices of the dequeued
# vertex s. If a adjacent has not been visited,
# then mark it visited and enqueue it
for i in self.graph[s]:
if visited[i] == False:
queue.append(i)
visited[i] = True
from pythonds.graphs import Graph, Vertex
from pythonds.basic import Queue
def bfs(g,start):
start.setDistance(0)
start.setPred(None)
vertQueue = Queue()
vertQueue.enqueue(start)
while (vertQueue.size() > 0):
currentVert = vertQueue.dequeue()
for nbr in currentVert.getConnections():
if (nbr.getColor() == 'white'):
nbr.setColor('gray')
nbr.setDistance(currentVert.getDistance() + 1)
nbr.setPred(currentVert)
vertQueue.enqueue(nbr)
currentVert.setColor('black')
Special challenge: Source