I’m not finding the highest value in a list with random values

Asked

Viewed 52 times

-1

I need to find the highest value in a list of 50 random numbers. To generate these numbers, I used the functions sample and randint. So to generate the list I use:

lista = [sample(range(0, 200), 50)]

And to find the biggest one I use:

mai = 0
for v in lista:
    if v == 0:
        mai = v
    else:
        if v > mai:
            mai = v
print(f'O maior valor da lista é {mai}')

But whenever I use some of these functions it returns this error: TypeError: '>' not supported between instances of 'list' and 'int' and if I generate a list manually, this method of finding the biggest one works perfectly, what can I do to get around this problem? I’ve tried to put the generated list inside another list and it still doesn’t work, if anyone can help I would be grateful.

2 answers

2

Another more pythonic way to respond is by using the function max which is provided by python.

from random import sample
lista = sample(range(0, 200), 50)
print('O maior elemento é: {}'.format(max(lista)))

1


You get this error because you are adding brackets to your sample, but the sample function already returns a list.

Random.sample(Population, k) Return a k length list of Unique Elements Chosen from the Population Sequence or set. Used for Random sampling without Replacement.

So the result you have is more or less like this:

   [[60, 93, 22, 57, 164, 79, 24, 92, 104, 114, 120, 59, 191, 137, 186, 31, 51, 35, 165, 18, 74, 95, 99, 116, 63, 141, 173, 105, 185, 27, 52, 80, 112, 159, 188, 67, 36, 108, 34, 1, 75, 40, 84, 138, 190, 119, 194, 6, 4, 82]]

When you get on the line if v > mai: you are comparing a list with an int.

To solve the problem just take the brackets out of your sample:

lista = sample(range(0, 200), 50)

Browser other questions tagged

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