Function that returns the element with more characters in a list

0

I came up with the following function:

def func6a(lista):
    maior = 0
    for el in lista:
        if type(el) == list:
            maior  = func6a(el)
        else:
            if len(el) > maior:
                maior = el

    return maior

But unfortunately, I'm having the following error:

  

* if len (el) > greater:

     

TypeError: '>' not supported between instances of 'int' and 'str' *

My question is; How can I escape this error? I expected it, but I do not know how to escape!

Note: Parameters must be strings or nested lists containing strings!

    
asked by anonymous 27.05.2018 / 23:34

4 answers

4

The other answers already present the corrected / working code, and interesting alternatives, but do not detail the problem, which is important to avoid / correct future similar errors.

Notice the error message:

  

TypeError: '>' not supported between instances of 'int' and 'str' *

This tells you that you are comparing an integer to a string, which you can not do.

And it happens in this line:

if len(el) > maior:

Now you may be wondering what kind of thing to generate this error? Something that can respond if you do a test table , and that is important for when you are not viewing the problem. But I help you better understand the problem without having to do a full-table test, and just analyze the values of the variables only in the first two steps.

It turns out that you set maior to the top as 0 , so when passing a list of simple strings as func6a(["abcd","cdf","gh"]) the first comparison will be between 4 ( "abcd" size) and 0 Working perfectly. But in this case it goes inside if and changes the value of greater:

if len(el) > maior:
    maior = el

maior now becomes "abcd" because you assigned the string in it, which means that the comparison will then be between 3 ( "cdf" size) and "abcd" resulting in error, because it is comparing 3 , which is a int , with "cdf" which is a string.

Also, if you return a int at the end of the function you will never get the answer you want from "element with more characters in a list" because the return is the size of the element and not the element.

    
28.05.2018 / 12:15
2

Considering the title of your question

Function that returns the element with more characters in a list

The built-in function max of python does what you need.

l = ['A', 'ABCDEFG', 'ABC']
max(l, key=len)
'ABCDEFG'

Considering the remark you made in the question

Note: Parameters must be strings or nested lists containing strings!

The function below with small adjustments for cases where the items in the list are not strings, I think it's useful.

def max_in_list(l):
    max_value = ''

    for _ in l:
        if isinstance(_, list):
            max_value = max_in_list(_)

        if len(_) > len(max_value):
            max_value = _

    return(max_value)

Execution should return the item with the largest character number, whether inside a nested list or outside.

ll = [ ['asas', 'sasas', 'a'], [ ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'a'  ] ] ]

max_in_list(ll)
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'

ll = [ ['asas', 'sasas', 'a'], ['ssasas', 's', 'aaaaaaaaaaaaaaa'], 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa']

max_in_list(ll)
        'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
    
28.05.2018 / 00:29
1

Well, I think you're comparing size of lists so you have to get the size of the largest len variable (greater):

def func6a(lista):
    maior = 0
    for el in lista:
        if type(el) == list:
            maior  = func6a(el)
        else:
            if len(el) > len(maior):
                maior = el

    return maior
    
27.05.2018 / 23:40
0

One way to work with multilevel lists, that is, to have lists of lists of lists of lists of string , is to represent all these data flatly, as if were only on one level. You can do this as follows:

def flatten(data):
    """ Representa uma lista|tupla multiníveis de maneira plana.

    Parâmetros:
        data (list|tuple): Iterável com as informações a serem planificadas.

    Retorno:
        Retorna um gerador com os dados de entrada em sua forma plana.

    Exemplo:

    >>> data = ['anderson', ['carlos', ['woss']]]
    >>> list(flatten(data))
    ['anderson', 'carlos', 'woss']
    """
    for item in data:
        if isinstance(item, (list, tuple)):
            yield from flatten(item)
        else:
            yield item

So, just use the max native function, correctly setting the key parameter to search for the string with the largest number of characters:

maior_string = max(data, key=len)

So the return will be the string with the largest number of characters, as expected.

strings = [
    'anderson',
    [
        'carlos',
        [
            'woss',
            'stackoverflow'
        ]
    ]
]

maior_string = max(flatten(strings), key=len)

print(f'O maior texto encontrado foi: {maior_string}')

See working at Repl.it | Ideone | GitHub GIST

    
28.05.2018 / 15:42