(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.
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