I have created the following program. It takes an input G, which consists of the vertices of a graph, along with the edges and the corresponding edge weights. The aim of the program is to extract just the edges
def edges(G):
E =[]
for i in G[1]:
E.append(i[0])
return E
print (edges(G))
On the following input
G = [({'a', 'b'}, 4), ({'a', 'c'}, 6), ({'a', 'd'}, 8), ({'b', 'e'}, 1) ,
({'b', 'f'}, 9), ({'c', 'f'}, 3), ({'d', 'g'}, 7), ({'d', 'h'}, 0)]
The following output is produced:
[{'a', 'b'}, {'a', 'c'}, {'a', 'd'}, {'e', 'b'}, {'f', 'b'}, {'f', 'c'}, {'g', 'd'}, {'h', 'd'}]
The output I am trying to get is:
[{'a', 'b'}, {'a', 'c'}, {'a', 'd'}, {'b', 'e'}, {'b', 'f'}, {'c', 'f'}, {'d', 'g'}, {'d', 'h'}]
Can anyone explain why the tuples I have extracted are reordered?
A set
is an unordered collection. What you are requesting is not possible.
The best you can do is use an ordered collection, such as list
or tuple
. Below is an example.
res = [tuple(sorted(x[0])) for x in G]
print(res)
[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'e'),
('b', 'f'), ('c', 'f'), ('d', 'g'), ('d', 'h')]
This is also possible functionally, but messy since Python has no native function composition. For composition, you can use 3rd party library toolz
.
from operator import itemgetter
from toolz import compose
res = list(map(compose(tuple, sorted, itemgetter(0)), G))