get the 3 largest numbers from a list in python

1

Can someone help me find the error?

  

"

"

"

"

    # TODO: implement this function

    def top_three(input_list):
        list1 = [2,3,5,6,8,4,2,1]
        input_list = sorted(list1, reverse=True)
        return input_list[:3]
    print (top_three(1))
    
asked by anonymous 23.07.2017 / 02:15

3 answers

2

Heapq

An alternative would be to use heapq:

import heapq  
lst = [2, 3, 5, 6, 8, 4, 2, 1]

# Os 3 maiores:
heapq.nlargest(3,lst)
[8, 6, 5]

# Os 3 menores
heapq.nsmallest(3,lst)
[1, 2, 2]
    
23.07.2017 / 17:03
3

You have two problems there. One of them is that you are limiting the data in the list twice: when calling the function, you must pass your entire list out of order - and it will return the 3 largest values. When writing the function call as top_three(input_list[:2])) you are only passing the first three values of your list, in the order they are found. The function will "see" a sub-ista with only these three values, and obviously say that they are the three largest.

Now another problem is that you are not actually using the value passed to the function - in the first line inside the function top_three you do input_list = [2,3,5,6,8,4,2,1] - and this over-writes the list passed as parameter to the function - and it will always work with the same numbers.

    
23.07.2017 / 07:47
0

It worked like this:

def top_three(input_list):
    input_list.sort()
    tops=input_list[-3:]
    q=sorted(tops, reverse=True)
    return q

list1 = top_three([2,3,5,6,8,4,2,1])
print (list1)
    
24.07.2017 / 17:22