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))
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))
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]
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.
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.
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)