Reputation:
The tuple G contains the set of edges, the set of vertices, and the weight of the edges.
#Weighted Graph
G = [['a', 'b' , 'c' , 'd']
[({'a', 'b'}, 4), ({'a', 'c'}, 6), ({'a', 'd'}, 8)]
I am trying to return the weight of an edge, given an edge. For example, for the edge {'a', 'b'}, I am trying to return the value 4. Is it possible to search for {'a', 'b'} and return this value?
Upvotes: 1
Views: 111
Reputation: 133
you can store start and end point of each edge in two tuples: E1 and E2. additionally you may store weight of each edge into tuple W and search for appropriate edge by iterating through elements of E1 and E2 finally you can access to appropriate weight by using W tuple.
G = ('a', 'b', 'c', 'd')
E1 = ('a', 'a', 'a')
E2 = ('b', 'c', 'd')
W = (4, 6, 8)
for i in range(len(E1)):
if E1[i] == 'a' and E2[i] == 'b':
print(W[i])
Upvotes: 0
Reputation: 107287
You can do that by looping over the second list inside G
but basically list is not a proper data structure for representing a graph.
As a more optimized and Pythonic way you can preserve them in a dictionary and access to each edge using a simple indexing.
There's one thing you should note though. set
s are not hashable and you have to use tuple
or another hashable iterator like frozenset
for preserving your edges as the dictionary keys.
In [20]: nodes, edges = G[0], {tuple(i): j for i, j in G[1]}
In [21]: edges
Out[21]: {('a', 'b'): 4, ('a', 'c'): 6, ('a', 'd'): 8}
In [22]: edges[('a', 'b')]
Out[22]: 4
Note that here I'm converting your current data to a dictionary but if you are generating this data by yourself it's better to do this at that level and create a dictionary at the first place before creating a nested list like this.
Upvotes: 2