Determining sequence of numbers with bubble sort from a txt file in python?

2

I have an input file in txt with data type the following:

7 6 8

4 8 5

0 1 2

1 0 3

2 3 0

This file is about 3 students from a school. The first line is the age of these 3 students (the first column could be student1, the second student2 and the third student3). The second line is the grade of the tests of these three students and line 3 to 5 corresponds to a matrix with the distance of these students in portfolios. (For example, in row three: first column - the distance from student1 to student1 is 0. Second column - the distance from student1 to student2 is 1 portfolio. Third column - the distance from student1 to student 2. The same idea for the lines 4 and 5.

I need a code that uses bubble sort to sort and read this txt file and sort the information according to the child's highest age and the other lines follow this order.

So the program should return:

6 7 8

8 4 5

0 1 3

1 0 2

3 2 0

So far I've been able to make a code that orders only the first line, with no connection to the second line and array. The code is as follows:

#lendo o arquivo com os dados no modo read.
arquivo = open('alunos.txt','r'); 

#lê uma linha do arquivo de texto
linha = arquivo.readline()

#Fecha o arquivo de texto
arquivo.close()

#Cria uma lista substituindo os espaços por virgulas
lista = linha.rsplit("  ")

#Determina o tamanho da lista para as condições do  bubble sort
tam_entrada = len(lista)

#Bubble Sort
for i in range (tam_entrada):
    for j in range (1, tam_entrada-i):
        if lista[j] < lista[j-1]:
            lista[j], lista[j-1] = lista[j-1], lista[j]

#Imprime a lista depois da utilização do bubble sort
print ("A ordem dos alunos classificados de acordo com a idade é: \n", lista)

Can anyone help me complete the code or maybe help me with new ideas?

Thank you very much!

    
asked by anonymous 17.07.2018 / 22:53

1 answer

2

First of all, let's create two functions that will help us.

The first function receives a line from the file and returns a list of integers.

def parse(linha):
    return [int(x) for x in linha.split()]

The second function does the opposite, takes a list and returns a line:

def emitir(valores):
    return ' '.join(map(str, valores))

Now we can start with the logic of the program.

First, let's read the lines from the original file:

with open('arquivo.txt') as f:
    linhas = f.readlines()

Once this is done, let's separate the first and second lines, each in a variable:

idades = parse(linhas[0])
notas = parse(linhas[1])
Here comes a trick. Let's transpose the values, so we create a list in which each item is a tuple with the student's age, his grade and his index in the original file. This will make sorting easier.

alunos = zip(idades, notas, range(len(idades)))

Now let's sort the values. I'm going to use the default Python function, you can create one with bubblesort if you want (this will not make any difference). After sorting, we have to undo the transposition to make writing the final file easier.

alunos = sorted(alunos)
idades, notas, indices = zip(*alunos)

The time has come to read the distances between each student. Let's create a dictionary that receives the index of two students and returns the distance between them. Note that the distance between the student i and j is the same between j and i (obviously).

distancias = {}

for i, linha in enumerate(linhas[2:]):
    for j, distancia in enumerate(parse(linha)):
        distancias[i, j] = distancia
        distancias[j, i] = distancia

All data is processed, so we have to create the output. Note that the final array is generated from the original distance between the students, but in the order in which they appear after sorted.

output = ''
output += emitir(idades) + '\n'
output += emitir(notas) + '\n'
output += '\n'.join(emitir(distancias[i, j] for j in indices) for i in indices)

The last step is to write the final file:

with open('final.txt', 'w') as f:
    f.write(output)

The output of the file is:

6 7 8
8 4 5
0 1 3
1 0 2
3 2 0

I have a challenge for you:

Note that the distance matrix is mirrored (the lower diagonal is the upper diagonal mirror). Currently the variable matriz saves all values, including duplicates. Is it possible to generate the same output without duplicating any value?

    
18.07.2018 / 21:11