Compute number of neighbors for each node
How do you evaluate whether a node is an important one or not? There are a few ways to do so, and here, you're going to look at one metric: the number of neighbors that a node has.
Every NetworkX graph G
exposes a .neighbors(n)
method that returns an iterator of nodes that are the neighbors of the node n
. To begin, use this method in the IPython Shell on the Twitter network T
to get the neighbors of of node 1
. This will get you familiar with how the function works. Then, your job in this exercise is to write a function that returns all nodes that have m
neighbors.
This is a part of the course
“Introduction to Network Analysis in Python”
Exercise instructions
- Write a function called
nodes_with_m_nbrs()
that has two parameters -G
andm
- and returns all nodes that havem
neighbors. To do this:- Iterate over all nodes in
G
(not including the metadata). - Use the
len()
andlist()
functions together with the.neighbors()
method to calculate the total number of neighbors that noden
in graphG
has.- If the number of neighbors of node
n
is equal tom
, addn
to the setnodes
using the.add()
method.
- If the number of neighbors of node
- After iterating over all the nodes in
G
, return the setnodes
.
- Iterate over all nodes in
- Use your
nodes_with_m_nbrs()
function to retrieve all the nodes that have 6 neighbors in the graphT
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Define nodes_with_m_nbrs()
def ____:
"""
Returns all nodes in graph G that have m neighbors.
"""
nodes = set()
# Iterate over all nodes in G
for n in ____:
# Check if the number of neighbors of n matches m
if ____ == ____:
# Add the node n to the set
____
# Return the nodes with m neighbors
return nodes
# Compute and print all nodes in T that have 6 neighbors
six_nbrs = ____
print(____)