45 lines
1.3 KiB
Python
45 lines
1.3 KiB
Python
# see the overview from 2026.07.31
|
|
|
|
sample_graph = {
|
|
'Alice': set(['Bob', 'Carol']),
|
|
'Bob': set(['Alice', 'Dave']),
|
|
'Carol': set(['Alice', 'Eve', 'Mallory']),
|
|
'Dave': set(['Frank', 'Eve', 'Bob']),
|
|
'Eve': set(['Carol', 'Grace', 'Dave']),
|
|
'Frank': set(['Dave', 'Heidi']),
|
|
'Grace': set(['Eve', 'Ivan', 'Mallory']),
|
|
'Heidi': set(['Frank', 'Ivan']),
|
|
'Ivan': set(['Heidi', 'Grace']),
|
|
'Mallory': set(['Carol', 'Grace'])
|
|
}
|
|
|
|
# This is an in-progress exercise
|
|
|
|
def nth_degree_connections(
|
|
graph: dict[str, set[str]],
|
|
starting_vertex: str,
|
|
max_n: int
|
|
):
|
|
checkinglist=[[starting_vertex,0]]
|
|
listvisited=list()
|
|
x=[0,0]
|
|
while len(listvisited)!=len(graph) and checkinglist!=[] and x[1]<max_n:
|
|
x=checkinglist[0]
|
|
if x[0] not in listvisited:
|
|
listvisited.append(x)
|
|
for y in graph[x[0]]:
|
|
if y not in listvisited:
|
|
listvisited.append(y)
|
|
checkinglist.append([y,x[1]+1])
|
|
checkinglist.pop(0)
|
|
return listvisited
|
|
|
|
|
|
print(nth_degree_connections(sample_graph, 'Mallory', 2))
|
|
print(nth_degree_connections(sample_graph, 'Alice', 4))
|
|
print(nth_degree_connections(sample_graph, 'Ivan', 1))
|
|
print(nth_degree_connections(sample_graph, 'Grace', 0))
|
|
print(nth_degree_connections(sample_graph, 'Carol', 100))
|
|
|
|
|