Find smallest string from a python list

Asked

Viewed 2,031 times

4

how do I do a function to determine the smallest string in a list by entering spaces?

For example, when typing:

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

the output must return "a" (no spaces), as it is the smallest string (ingnorando spaces).

Here’s the code I tried:

def menor_nome(nome):
    m = min(nome)
    m = m.strip
    return m
  • Output must return only the character a or the actual value in the list including whitespace?

  • the output must return only {a}

  • You can [Edit] the question and add the code you tried to do?

  • without spaces, and without parentheses

  • of course, I edit now

  • finished work friend, edited the question! See if you are better

  • Only the () in the method call strip. Put them on and it should work.

  • OK, I’ve done it. Thank you very much

Show 4 more comments

2 answers

4


Edited (New version):
Actually my original version is totally wrong, I did not notice the fact that what the question asks is the smallest "size" of the string and not the smallest value. As I also noticed that the other answer was not completely correct, since it did not take into account the Code of the strings and even when there are more than two strings with the same size as the minimum, I decided to make a new version.

Obs. Obviously I considered that the list always has the same type of data, in the case of strings, because it would not make sense to mistrust strings and numerics in this context. For numeric it 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 working code here.


Original version

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

:-)

  • thank you very much friend! Broke a branch

  • Give the acceptance and the upvote, Please. :-)

  • Thanks for the feedback! Votes from users with less than 15 reputation are recorded, but do not change the score shown in the post. I don’t have how, pardon. But I gave the "accept"

  • Really, I forgot about it. Thanks.

  • Guy just an observation to his code.

  • by entering the following list: ['maria', 'josé', 'PAULO', 'Catarina']. The expected result would be josé, however I got Catarina

  • you know how to proceed so that the exit is josé?

  • Okay, actually I’m seeing that neither my answer nor the other one are totally correct, I’m going to edit it for a new version.

  • After the edition of the last version I realized that I had forgotten the strip(), corrected.

Show 5 more comments

2

The min function will return the smallest element in the list. However, it is necessary 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 will return the smallest considering the alphabetical order. And understand that space comes before the a. That way, space needs to be removed before the sorting of the function returns the result you expect. I changed your array a little to 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 passing a lambda function that will strip for 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 what you need is the string with the smallest number of characters ignoring the spaces, use the lambda function below. It will return the size of each string (without 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
  • thanks, friend. The best answer and best explained

Browser other questions tagged

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