Data loaded from the file is not returned in the correct order

19 views Asked by At

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?

1

There are 1 answers

0
patda9 On BEST ANSWER

Using edges = set() makes your result unordered. There is no direct way to use ordered set in python execpt using ordered_set package or you can try (not so clean way) to create an ordered set from a dictionary keys.

def get_edges_set(lines):
  edges = {}
  for line in lines[1:]:
    edge = line.strip().split()
    edges['-'.join(edge)] = None # set a key-value pair to the dictionary
  return list(edges.keys())