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])
Thanks, I didn’t know about the key parameter in Sorted().
– Daniel Nishimori