My code is only returning half of what it should

Asked

Viewed 102 times

3

I’m doing some simple exercises in Python and this code should return a list organized by the size of the fruit name, with the fruit with the shortest name first (in case, 'uva').

lista = ['maça', 'canela', 'morango', 'uva', 'pera', 'laranja', 'banana', 'tomate', 'toranja', 'amora']
retorno = []
nome = "a"*15

while len(retorno) < len(lista):
    for nome_atual in lista:
        if len(nome_atual) < len(nome):
            nome = nome_atual
    else:
        retorno.append(nome)
        lista.remove(nome)
        nome = "a"*15

print(retorno)

Of 10 items, the return list only has half.

['uva', 'maça', 'pera', 'amora', 'canela']

Why is this happening?

2 answers

3


The problem is in the condition while len(retorno) < len(lista).

Basically, you remove an element from the original list when it is inserted into the result. Then when the list retorno has 5 elements, the original list will also have 5 elements remaining, and as their sizes are now equal, the condition of the while is no longer satisfied, closing the loop.

So what you should do is iterate while you have elements in the original list, ie, while len(lista) > 0.


But actually all of this is very inefficient, because you go through the list over and over again without need. If you want to sort the elements by size, just do:

retorno = sorted(lista, key=len)

Because it already returns the ordered list the way you want it: the parameter key indicates the criterion to be used, which in this case is the function len.


It is also worth remembering that sorted returns another list, keeping the original intact.

But if you want to order your own list without creating a new one, just use the method sort:

lista.sort(key=len)
print(lista)
  • Thanks, I didn’t know about the key parameter in Sorted().

2

One of the ways you can solve this question is by using one of the sorting algorithms. In this question I will give two examples using the sorting algorithm bubble sort.

The first algorithm will use the loop of repetition for, that we can implement as follows:

lista = ['maça', 'canela', 'morango', 'uva', 'pera', 'laranja', 'banana', 'tomate', 'toranja', 'amora']

n = len(lista)
for i in range(n - 1, 0, -1):
    for j in range(i):
        if len(lista[j]) > len(lista[j + 1]):
            lista[j], lista[j + 1] = lista[j + 1], lista[j]

print(lista)

And the second algorithm will use the loop of repetition while, that we can implement as follows:

lista = ['maça', 'canela', 'morango', 'uva', 'pera', 'laranja', 'banana', 'tomate', 'toranja', 'amora']

n = len(lista)
while n > 0:
    i = 0
    while i < n - 1:
        if len(lista[i]) > len(lista[i + 1]):
            lista[i], lista[i + 1] = lista[i + 1], lista[i]
        i += 1
    n -= 1

print(lista)

Note that both codes sort the words in ascending order of size, i.e., from smaller word to larger word size. Also note that there was no need to create another list. For, what each of these algorithms does is simply sort the list elements.

Running one of the two codes you will get the following result:

['uva', 'maça', 'pera', 'amora', 'canela', 'banana', 'tomate', 'morango', 'laranja', 'toranja']

Now, by chance, in the near future, you want to sort the words of the same size in alphabetical order, you can use their codes.

lista = ['maça', 'canela', 'morango', 'uva', 'pera', 'laranja', 'banana', 'tomate', 'toranja', 'amora']

n = len(lista)
for i in range(n - 1, 0, -1):
    for j in range(i):
        if len(lista[j]) > len(lista[j + 1]) or \
                (len(lista[j]) == len(lista[j + 1]) and lista[j] > lista[j + 1]):
            lista[j], lista[j + 1] = lista[j + 1], lista[j]

print(lista)

or...

lista = ['maça', 'canela', 'morango', 'uva', 'pera', 'laranja', 'banana', 'tomate', 'toranja', 'amora']

n = len(lista)
while n > 0:
    i = 0
    while i < n - 1:
        if len(lista[i]) > len(lista[i + 1]) or \
                (len(lista[i]) == len(lista[i + 1]) and lista[i] > lista[i + 1]):
            lista[i], lista[i + 1] = lista[i + 1], lista[i]
        i += 1
    n -= 1

print(lista)

Note that these last two codes have a condition to alphabetically sort the words, which may have the same size.

This condition is in the following code line:

(len(lista[j]) == len(lista[j + 1]) and lista[j] > lista[j + 1])

Browser other questions tagged

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