Bubblesort in key 3 of a tuple?

Asked

Viewed 38 times

0

I own a tuple with the following values:

('beringela', 10, 1.99)
('arroz', 5, 4.99)
('peixe', 2, 9.99)
('abacaxi', 100, 3.99)

I must order it by the third column, but I cannot use Builtin organization methods from Python3, I mean, I need to make my own produtos.sort(key=lambda x: x[3]) in hand.

To sort through the first and second field I used Bubblesort, but I’m not able to use it for the third field. Follow the code I used for the first two fields:

def ordenaCampoUm(produtos):
    tam = len(produtos)
    for i in range(tam):
        troca = False
        for j in range(1, tam-i):
            if produtos[j] < produtos[j-1]:
                produtos[j], produtos[j - 1] = produtos[j-1], produtos[j]
                troca = True
        if not troca:
            break

    print("----- Listagem dos Produtos Ordenados Pelo Campo: 1 -----")
    for linha in produtos:
        print(tuple(linha))
    print("-----------------------------------------------------------------------")
    print()

def ordenaCampoDois(produtos):
    tam = len(produtos)
    for i in range(tam):
        for j in range(0, tam-i-1):
            if produtos[j][1] > produtos[j+1][1]:
                temp = produtos[j]
                produtos[j] = produtos[j+1]
                produtos[j+1] = temp

    print("----- Listagem dos Produtos Ordenados Pelo Campo: 2 -----")
    for linha in produtos:
        print(tuple(linha))
    print("-----------------------------------------------------------------------")
    print()

Some light on how to solve?

  • But the ordering is the same in the 3 fields, why will you have three functions that do the same thing? It is not easier to implement the parameter key in its function and use it to sort the 3 fields?

1 answer

0


You can create your own parameter key that will take the value to make the comparison between values. So instead of doing:

if a > b:

You do:

if key(a) > key(b)

Example

def bubble_sort(lista, key):
    while True:
        trocou = False

        for i in range(len(lista) - 1):
            if key(lista[i]) > key(lista[i+1]):
                lista[i], lista[i+1] = lista[i+1], lista[i]
                trocou = True

        if not trocou:
            break

    return lista

Code in the Repl.it


Now just select which item will be used in comparison.

print('=== ordenado por nome')
for x in bubble_sort(dados, lambda x: x[0]):
    print(x)


print('=== ordenado por qtde')
for x in bubble_sort(dados, lambda x: x[1]):
    print(x)


print('=== ordenado por preco')
for x in bubble_sort(dados, lambda x: x[2]):
    print(x)

The exit would be:

=== ordenado por nome
('abacaxi', 100, 3.99)
('arroz', 5, 4.99)
('beringela', 10, 1.99)
('peixe', 2, 9.99)

=== ordenado por qtde
('peixe', 2, 9.99)
('arroz', 5, 4.99)
('beringela', 10, 1.99)
('abacaxi', 100, 3.99)

=== ordenado por preco
('beringela', 10, 1.99)
('abacaxi', 100, 3.99)
('arroz', 5, 4.99)
('peixe', 2, 9.99)

Explanation

The only modification made to the method bubble_sort "normal" is that the comparison is not made directly with the values of the list but with a "modified version" by a function. Just return the values you want to compare for sorting.

In your case, you want to compare the 3rd element of the tuple, which is the item to be ordered. So you just make a function that takes this tuple and returns only the 3rd element.

def pega_terceiro(minha_tupla):
    return minha_tupla[2]

bubble_sort(dados, pega_terceiro)

This way the comparison between the elements of the list will be made using only the 3rd element of each tuple, as you wish.

In python you can also create a function lambda, which is a simple and short anonymous function.

The following function has the same effect as the pega_terceiro of the above code:

lambda minha_tupla: minha_tupla[2]

For knowledge purposes, python has a module called operator. This module contains the function itemgetter, whose goal is to return another function that accesses item N of an iterable.

This means that the 3 functions below play the same role in our sorting method:

from operator import itemgetter

def pega_terceiro(minha_tupla):
    return minha_tupla[2]

pega_terceiro = lambda minha_tupla: minha_tupla[2]

pega_terceiro = itemgetter(2)
  • The tip you gave worked, but you can explain me better about this line if key(lista[i]) > key(lista[i+1]): or indicate to me some material that can help me? I didn’t quite understand how the lambda x: x[1] for example would enter in place of key.

  • I will create the session to explain better. I just can’t right now, this afternoon supplement the question

  • @Caiotracera complemented the answer. Now it should be clearer what was done. I linked the documentation in the important points to have references.

Browser other questions tagged

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