Specifying a weight on edges
Weights can be added to edges in a graph, typically indicating the "strength" of an edge. In NetworkX, the weight is indicated by the 'weight'
key in the metadata dictionary.
Before attempting the exercise, use the IPython Shell to access the dictionary metadata of T
and explore it, for instance by running the commands T.edges[1, 10]
and then T.edges[10, 1]
. Note how there's only one field, and now you're going to add another field, called 'weight'
.
Cet exercice fait partie du cours
Introduction to Network Analysis in Python
Instructions
- Set the
'weight'
attribute of the edge between node1
and10
ofT
to be equal to2
. Refer to the following template to set an attribute of an edge:network_name.edges[node1, node2]['attribute'] = value
. Here, the'attribute'
is'weight'
. - Set the weight of every edge involving node
293
to be equal to1.1
. To do this:- Using a
for
loop, iterate over all the edges ofT
, including themetadata
. - If
293
is involved in the list of nodes[u, v]
:- Set the weight of the edge between
u
andv
to be1.1
.
- Set the weight of the edge between
- Using a
Exercice interactif pratique
Essayez cet exercice en complétant cet exemple de code.
# Set the weight of the edge
____ = 2
# Iterate over all the edges (with metadata)
for u, v, d in ____:
# Check if node 293 is involved
if 293 in ____:
# Set the weight to 1.1
____ = 1.1