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:7 | ISBN:978013274719 | Edition: 6

Question

(Count single digits) Write a program that generates 1,000 random integers between 0 and 9 and displays the count for each number. (Hint: Use a list of ten integers, say counts, to store the counts for the number of 0s, 1s, ..., 9s.)

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Program code:

import random

# Initialize a list of counts for each number from 0 to 9
counts = [0] * 10

# Generate 1,000 random integers between 0 and 9
for _ in range(1000):
    number = random.randint(0, 9)
    counts[number] += 1

# Display the count for each number
for i in range(10):
    print(f"Count of {i}: {counts[i]}")

Output of the program code:

Output 1:

Count of 0: 94
Count of 1: 121
Count of 2: 93
Count of 3: 90
Count of 4: 96
Count of 5: 103
Count of 6: 117
Count of 7: 81
Count of 8: 108
Count of 9: 97

Output 2:

Count of 0: 94
Count of 1: 121
Count of 2: 93
Count of 3: 90
Count of 4: 96
Count of 5: 103
Count of 6: 117
Count of 7: 81
Count of 8: 108
Count of 9: 97

 

0 0

Discussions

Post the discussion to improve the above solution.