Function that returns the element with more characters from a list

Asked

Viewed 725 times

0

I arrived at 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,:

*if Len(el) > larger:

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

My question is: how can I escape this error ? I’ve been waiting for you, but I don’t know how to escape!

Obs: parameters must be strings or nested list containing strings!

4 answers

5

The other answers already feature fixed/working code, and interesting alternatives, but do not detail the problem, which is important to be able to prevent/correct similar future errors.

Note 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 cannot do.

And it happens on this line:

if len(el) > maior:

Now you might be wondering what kind of things to make this mistake? Something you can answer if you make one table test, and that it’s important for when you’re not visualizing the problem. But I help you better understand the problem without having to do a full table test, and analyzing only the values of the variables in the first two steps.

Turns out you set maior up there like 0, so when passing a list of simple strings like func6a(["abcd","cdf","gh"]) the first comparison will be between 4(size of "abcd") and 0 working perfectly. But in this case gets inside the if and exchange the higher value:

if len(el) > maior:
    maior = el

Now the maior became "abcd" because you assigned the string to it, which means that next the comparison will be between 3(size of "cdf") and "abcd" resulting in error as it is comparing 3, which is a int, with "cdf" which is a string.

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

2

Considering the title of your question

Function that returns the element with more characters from a list

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

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

Considering the remark you made in the question

Obs: parameters must be strings or nested list containing strings!

The function below with small adjustments for cases where list items are not strings, I believe it is 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 must return the item with the highest character number, whether it is 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'
  • max(['A', 'ABCDEFG', 'ABC', 'B']) returns 'B', then the first part of your answer is wrong. The function max returns the largest string in alphabetical order, without taking into account their size.

  • Adinanp, thanks for the explanation, it turns out the idea is not to use native functions in python. The teacher does not allow, my mistake not punctuate it in the statement,!

  • Anderson, you’re right. I saw that in your answer you make the right use of max with the argument key. I edited my reply, thank you for pointing out the error.

1

Well, I believe you’re comparing list sizes so you have to get the size of the larger variable):

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

0

A way to work with multilevel lists, that is, allow you to have lists of lists of lists of lists of... of string, is to represent all these data flat, as if they were only on one level. It is possible to do it 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 native function max, by correctly defining the parameter key to get the string with the highest number of characters:

maior_string = max(data, key=len)

So the return will be to string with a greater 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 on Repl.it | Ideone | Github GIST

  • Anderson, thank you for the explanation and really your code is great. However, I am a beginner and this exercise is from a class,the teacher restricted so that we do it in the simplest way possible,therefore, I appreciate your explanation and code,but I need it in a simpler way.Hug!

Browser other questions tagged

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