SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Y Daniel Lang
Chapter:
Sets And Dictionaries
Exercise:
Programming Excercises
Question:2 | ISBN:978013274719 | Edition: 6

Question

(Count occurrences of numbers) Write a program that reads an unspecified number of integers and finds the ones that have the most occurrences. For example, if you enter 2 3 40 3 5 4 –3 3 3 2 0, the number 3 occurs most often. Enter all numbers in one line. If not one but several numbers have the most occurrences, all of them should be reported. For example, since 9 and 3 appear twice in the list 9 30 3 9 3 2 4, both occurrences should be reported.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Count occurrences of numbers Program code:

def findMostFrequentNums():
    # Read integers from user input
    numbers = input("Enter integer numbers: ").split()

    # Create a dictionary to store the count of each number
    counts = {}

    # Iterate over the numbers and count their occurrences
    for num in numbers:
        num = int(num)  # Convert the number from string to integer
        if num in counts:
            counts[num] += 1
        else:
            counts[num] = 1

    # Find the maximum count
    max_count = max(counts.values())

    # Find the numbers with the maximum count
    findNums = [num for num, count in counts.items() if count == max_count]

    # Display the numbers with the maximum count
    print("The following are that occurs most often:")
    for num in findNums:
        print(num, end=" ")


# Run the function
findMostFrequentNums()

Executed Output 1:

Enter integer numbers: 3 40 3 5 4 -3 3 3 2 0
The following are that occurs most often:
3 

Executed Output 2:

Enter integer numbers: 3 40 3 5 4 -3 3 3 2 0
The following are that occurs most often:
3 

 

0 0

Discussions

Post the discussion to improve the above solution.