Finding nodes involved in triangles
NetworkX provides an API for counting the number of triangles that every node is involved in: nx.triangles(G). It returns a dictionary of nodes as the keys and number of triangles as the values. Your job in this exercise is to modify the function defined earlier to extract all of the nodes involved in a triangle relationship with a given node.
Diese Übung ist Teil des Kurses
Introduction to Network Analysis in Python
Anleitung zur Übung
- Write a function
nodes_in_triangle()that has two parameters -Gandn- and identifies all nodes in a triangle relationship with a given node.- In the
forloop, iterate over all possible triangle relationship combinations. - Check whether the nodes
n1andn2have an edge between them. If they do, add both nodes to the settriangle_nodes.
- In the
- Use your function in an
assertstatement to check that the number of nodes involved in a triangle relationship with node1of graphTis equal to35.
Interaktive Übung
Vervollständige den Beispielcode, um diese Übung erfolgreich abzuschließen.
from itertools import combinations
# Write a function that identifies all nodes in a triangle relationship with a given node.
def nodes_in_triangle(G, n):
"""
Returns the nodes in a graph `G` that are involved in a triangle relationship with the node `n`.
"""
triangle_nodes = set([n])
# Iterate over all possible triangle relationship combinations
for n1, n2 in ____:
# Check if n1 and n2 have an edge between them
if ____:
# Add n1 to triangle_nodes
____
# Add n2 to triangle_nodes
____
return triangle_nodes
# Write the assertion statement
assert len(____(____, ____)) == ____