user15250139
user15250139

Reputation:

If the largest number occurs more than once in the same list, how do I print them all out?

Here is my program,

empty_list = []
max_no = 0
for i in range(5):
    input_no = int(input("Enter a number: "))
    empty_list.append(input_no)
for x in empty_list:
    if x > max_no:
       max_no = x
high = empty_list.index(max_no)
print ([empty_list[high]])

Example list: [4, 3, 6, 9, 9]

Example output: [9]

How can I change my program to print out all the instances of the largest number occurring in the same list?

Expected output: [9, 9]

Upvotes: 1

Views: 478

Answers (3)

brejq_PL
brejq_PL

Reputation: 21

In order to find the biggest number, you can use the Python built-in function max()

max_no = max(empty_list)

In order to count them, you can use the count() method, like so:

count_no = empty.count(max_no)

Upvotes: 2

taesu
taesu

Reputation: 4580

You are asking, given a list with integers, you want a function that
returns a list with the largest integer N number of times where N is the
number of occurrence in the given list.

def foo(lst):
    r = max(lst) # find maximum integer in the list
    d = lst.count(r) # find how many times it occurs in the list
    return [r for i in range(d)] # create a list with the max int N number of times.
    
lst = [1,1,1,1,5,5,9]
print(foo(lst)) # prints [9]

lst = [1,1,1,1,5,5]
print(foo(lst)) # prints [5,5]

lst = [4, 3, 6, 9, 9]
print(foo(lst)) # prints [9,9]

Upvotes: 1

Unmitigated
Unmitigated

Reputation: 89294

You can store both the maximum number and the number of occurrences of that number.

empty_list = []
max_no = 0
times = 0
for i in range(5):
    input_no = int(input("Enter a number: "))
    empty_list.append(input_no)
for x in empty_list:
    if x > max_no:
       max_no = x
       times = 1;
    elif x == max_no:
        times += 1
print([max_no] * times)

Demo

Upvotes: 1

Related Questions