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:
0.lists
Exercise:
Programming Excercises
Question:3 | ISBN:978013274719 | Edition: 6

Question

(Count occurrence of numbers) Write a program that reads some integers  between 1 and 100 and counts the occurrences of each. Here is a sample run of the program:

Enter integers between 1 and 100: 2  5  6  5  4  3  23  43  2
2  occurs  2 times
3  occurs  1 time
4  occurs  1 time
5  occurs  2 times
6  occurs  1 time
23  occurs  1 time
43  occurs  1 time

Note that if a number occurs more than one time, the plural word “times” is used in the output.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Count occurrence of numbers Program code:

# Prompt the user to enter integers between 1 and 100
inputNums = input("Enter integers between 1 and 100 (space-separated): ").split()

# Convert the input strings to integers
numbers = [int(num) for num in inputNums]

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

# Count the repeatNums of each number
for number in numbers:
    if number in repeatNums:
        repeatNums[number] += 1
    else:
        repeatNums[number] = 1

# Display the repeatNums of each number
for number, count in repeatNums.items():
    if count > 1:
        plural = "times"  # Use plural "times" for counts > 1
    else:
        plural = "time"  # Use singular "time" for count = 1
    print(number, "occurs", count, plural)

Executed Output:

Enter integers between 1 and 100 (space-separated): 2 5 6 5 4 3 23 43 2
2 occurs 2 times
5 occurs 2 times
6 occurs 1 time
4 occurs 1 time
3 occurs 1 time
23 occurs 1 time
43 occurs 1 time

 

0 0

Discussions

Post the discussion to improve the above solution.