Mode
given a list of integers,write a program to print the mode.
mode - the most common value in the list. if multiple elements with same frequency are present, print all values with same frequency in increasing order.
input
the input will be a single line of containing space-separated integers.
output
the third line of output should contain the mode.
see sample input/output for the output format
explanation
for example, if the given list of integers are
2 6 3 1 8 12 2 9 10 3 4
the average of all the numbers is 4.67.
after sorting the array,
1 2 2 3 3 4 6 8 9 10 12
as 2 and 3 are having the same frequency , the mode will be 2 3.
so the output should be
Mode: 2 3
sample input 1
2 6 3 1 8 12 2 9 10 3 4
sample output 1
Mode: 2 3
line = input()
L = [int(s) for s in line.split()]
L.sort()
mode = []
fr = 0
max_fr = 0
prev_x = None
for x in L:
if prev_x is None:
fr = 1
elif x != prev_x:
if fr > max_fr:
max_fr = fr
mode = [prev_x]
elif fr == max_fr:
mode.append(prev_x)
fr = 1
else:
fr += 1
prev_x = x
for m in mode:
print(m, end=' ')
print()
Comments
Leave a comment