I have a simple program whose task is to read the graph description from a file and return the values.
file.txt:
4 5
1 2
2 3
3 4
1 4
2 4
where 4 represents the number of vertices of the graph, and 5 represents the number of edges of graph G (so I don't want to show that)
f = open('file.txt')
lines = f.readlines()
def get_edges_set(lines):
edges = set()
for line in lines[1:]:
edge = line.strip().split()
edges.add('-'.join(edge))
return edges
print(get_edges_set(lines))
I expect such output:
{1-2, 2-3, 3-4, 1-4, 2-4}
And I receive:
{'2-3', '2-4', '1-2', '3-4', '1-4'}
Where am I making a mistake, and why isn't it reading data from the file in the correct order?
Using
edges = set()makes your result unordered. There is no direct way to use ordered set in python execpt usingordered_setpackage or you can try (not so clean way) to create an ordered set from a dictionary keys.