Determine sequence of numbers with Bubble Sort from a python txt file?

Asked

Viewed 298 times

2

I have a txt input file with data type the below:

7 6 8

4 8 5

0 1 2

1 0 3

2 3 0

This file is about information for 3 students of a school. The first line is the age of these 3 students (the first column could be aluno1, the second aluno2 and the third aluno3). The second line is the grade of the tests of these three students and line 3 until 5 corresponds to a matrix with the distance of these students in portfolios. (For example, in row three: first column - the distance from aluno1 to aluno1 is 0. Second column - the distance from aluno1 to aluno2 is 1 wallet. Third column - distance from student to student 2. Same idea for 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 minor to the adult of the students and that the other lines follow this ordering.

Therefore, the program should return:

6 7 8

8 4 5

0 1 3

1 0 2

3 2 0

So far I have managed to make a code that ordered only the first line, without connection to the second line and the matrix. The code follows below:

#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 someone help me complete the code or maybe help me with new ideas?

Thank you very much!

  • 2

    NOTE: txt file does not have blank lines between rows and columns are separated by 2 spaces.

  • But ordination has to be specifically with Bubble Sort ? This is part of some exercise ?

1 answer

2

First of all, let’s create two functions that to assist us.

The first function takes 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 of 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 one into a variable:

idades = parse(linhas[0])
notas = parse(linhas[1])

Here comes a trick. We will 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 facilitate ordination.

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

Now let’s sort the values. I’ll use the default Python function, you can create one with bubblesort if you want (it won’t make a difference). After ordering, we have to undo the transposition to facilitate the writing of the final file.

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

It’s time 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 the data is processed, so we have to create the output. Note that the final matrix is generated from the original distance between students, but in the order in which they appear after ordered.

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 from 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. It is possible to generate the same output without duplicating any value?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.