LoslegenKostenlos loslegen

Visualizing connectivity

Here, you're going to visualize how the connectivity of the top connected nodes changes over time. The list of top connected values, top_connected, from the previous exercise has been loaded.

Remember the defaultdict you used in Chapter 1? You'll use another defaultdict in this exercise! As Eric mentioned in the video, a defaultdict is preferred here as a regular Python dictionary would throw a KeyError if you try to get an item with a key that is not currently in the dictionary.

This exercise will make use of nested for loops. That is, you'll use one for loop inside another.

Diese Übung ist Teil des Kurses

Intermediate Network Analysis in Python

Kurs anzeigen

Anleitung zur Übung

  • Initialize a defaultdict of empty lists called connectivity.
  • Iterate over top_connected using a for loop, and in the body of this outer for loop, once again iterate over Gs. Inside this nested loop:
    • The keys of connectivity should be the nodes n in top_connected, and the values should be the list of connectivity scores. Therefore, you have to append len(list(G.neighbors(n))) to connectivity[n].
  • Iterate over connectivity using .items() and plot the connectivity of each node by passing in conn to plt.plot().

Interaktive Übung

Versuche dich an dieser Übung, indem du diesen Beispielcode vervollständigst.

# Import necessary modules
import matplotlib.pyplot as plt
from collections import defaultdict

# Create a defaultdict in which the keys are nodes and the values are a list of connectivity scores over time
connectivity = ____
for n in ____:
    for g in ____:
        connectivity[____].____(len(____))

# Plot the connectivity for each node
fig = plt.figure() 
for n, conn in ____: 
    plt.plot(____, label=n) 
plt.legend()  
plt.show()
Code bearbeiten und ausführen