Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the largest number(s) in a list of elements, possibly non-unique?

Here is my program,

item_no = []
max_no = 0
for i in range(5):
    input_no = int(input("Enter an item number: "))
    item_no.append(input_no)
for no in item_no:
    if no > max_no:
       max_no = no
high = item_no.index(max_no)
print (item_no[high])

Example input: [5, 6, 7, 8, 8]

Example output: 8

How can I change my program to output the same highest numbers in an array?

Expected output: [8, 8]

like image 461
Justin Avatar asked Mar 18 '19 07:03

Justin


People also ask

What will be the most efficient approach to find the largest number in a list of 20 numbers?

Loved by our community. First find out the number which has the most digits. Then find out which has the highest tens digit. Then find out which has the highest units digit.

How do you find the largest number in a list in Python?

In Python, there is a built-in function max() you can use to find the largest number in a list. To use it, call the max() on a list of numbers. It then returns the greatest number in that list.

How do you find the three largest elements in an array?

Solution Approachif (arr[i] > max) -> max3 = max2, max2 = max , max = arr[i]. else if (arr[i] > max2) -> max3 = max2, max2 = arr[i]. else if (arr[i] > max3) -> max3 = arr[i]. At the end of the loop, we will print all three values.


2 Answers

Just get the maximum using max and then its count and combine the two in a list-comprehension.

item_no = [5, 6, 7, 8, 8]

max_no = max(item_no)
highest = [max_no for _ in range(item_no.count(max_no))]
print(highest)  # -> [8, 8]

Note that this will return a list of a single item in case your maximum value appears only once.


A solution closer to your current programming style would be the following:

item_no = [5, 6, 7, 8, 8]
max_no = 0  # Note 1 
for i in item_no:
    if i > max_no:
        max_no = i
        high = [i]
    elif i == max_no:
        high.append(i)

with the same results as above of course.

Notes

  1. I am assuming that you are dealing with N* (1, 2, ...) numbers only. If that is not the case, initializing with -math.inf should be used instead.

Note that the second code snippet is less efficient than the first by quite a margin. Python allows you to be more efficient than these explicit, fortran-like loops and it is more efficient itself when you use it properly.

like image 126
Ma0 Avatar answered Sep 29 '22 21:09

Ma0


You can do it even shorter:

item_no = [5, 6, 7, 8, 8]
#compute once - use many times
max_item = max(item_no)
print(item_no.count(max_item) * [max_item])

Output:

[8, 8]
like image 42
Allan Avatar answered Sep 29 '22 21:09

Allan