Find lower string of a list in python

4

How do I make a function to determine the smallest string in a list by ignoring spaces?

For example, when typing:

menor_elemento(["joão", "   a ", "arrozz"])

The output should return "a" (without spaces), because it is the smallest string (ignoring the spaces).

Here is the code I tried:

def menor_nome(nome):
    m = min(nome)
    m = m.strip
    return m
    
asked by anonymous 10.06.2017 / 17:11

2 answers

4
  

Edited (New version):
  Actually my original version is totally wrong, I did not pay attention to the fact that what the question asks for is the smallest "size" of the string and not the smallest value. As I also realized that the other answer was not totally correct, since it did not take into account the decode of the strings and nor when there are more than two strings with the size equal to the minimum, I decided to make a new version.

Obs. Obviously I considered that the list always has the same data type, in the case of strings, because it would not make sense of the mismatch of strings and numerics in that context. For numeric would be very easy to adapt the code, there goes:

DEMO

import unicodedata as ud

def min_list(_list_str):
    # Tamanho da lista
    len_list = len(_list_str)

    # Normalizando a lista (suprimindo acentos)
    list_str =  [  (ud.normalize('NFKD', s ).encode('ASCII','ignore').decode()).strip() for s in  _list_str]

    # Produz uma lista com os tamanhos de cada elemento
    lens = [len(s) for s in list_str]

    # Tamanho do menor (ou menores, quando empate) elemento
    min_len = min(lens)

    # Lista para guardar as strings cujos tamanhos sejam iguais ao minimo
    mins = []

    for i in range(len_list):
        # String normalizada
        s = list_str[i]
        if len(s)==min_len:
            mins.append(_list_str[i].strip() )

    return mins  


list_str = ['maria', 'josé', 'PAULO', 'Catarina]', ' kate  ', 'joão', 'mara' ]


print ( min_list(list_str) )
['josé', 'kate', 'joão', 'mara']

See the code here.

  

Original Version

min(["joão", "   a ", "arrozz"]).strip()
'a'

: -)

    
10.06.2017 / 17:24
2

The min function will return the smallest element in the list. However, you need to consider the type of elements in the list. In the case of numbers, the smallest number.

print('Exemplo 1')
menor = min([3, 4, 2, 1])
print(menor)

Out[]: Exemplo 1
Out[]: 1

In the case of a string, it returns the smallest considering the alphabetical order. And understand that space comes before a. That way, the space needs to be removed before the ordering of the function returns the result you expect. I've changed your array a bit so you can understand the problem. In example 2, you expect the result to be "a", but the return is "arrozz".

print('Exemplo 2')
menor = min(["joão", "   b   ", "   arrozz   ", "a"])
print(menor.strip())

Out[]: Exemplo 2
Out[]: arrozz

To get the expected result, use the key parameter by passing a lambda function that will strip each element.

print('Exemplo 3')
menor = min(["joão", "   b   ", "   arrozz   ", "a"], key=lambda x: x.strip())
print(menor.strip())

Out[]: Exemplo 3
Out[]: a   

If you need the string with the fewest number of characters ignoring spaces, use the lambda function below. It will return the length of each string (without the spaces) to be evaluated by the min function.

print('Exemplo 4')
menor = min(["joão", "   b   ", "   arrozz   ", "a"], key=lambda x: len(x.strip()))
print(menor.strip())

Out[]: Exemplo 4
Out[]: b
    
10.06.2017 / 19:24