0 votes
1 view
in Python by (8.3k points)

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]

1 Answer

0 votes
by (16.8k points)

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

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.

...