Reputation: 69
Write a program that generates 100 random integers for a list between 0 and 9 and displays the count for each time a number is present in the list. Been fumbling around with this for two days. Below is the closest of all the ugly hacks I've tried. My output is always zero for some reason using several attempts. Any help would be appreciated.
#Count single digits
import random
rand = []
num = 0
while num < 10:
num = num + 1
int = [random.randint(0, 9)]
#print(rand, end="")
rand.append(int)
print(rand)
print("")
print("Number of zeros is ", rand.count(0))
print("Number of ones is ", rand.count(1))
print("Number of twos is ", rand.count(2))
print("Number of threes is ", rand.count(3))
print("Number of fours is ", rand.count(4))
print("Number of fives is ", rand.count(5))
print("Number of sixes is ", rand.count(6))
print("Number of sevens is ", rand.count(7))
print("Number of eights is ", rand.count(8))
print("Number of nines is ", rand.count(9))
Output:
[[8], [6], [1], [8], [7], [0], [4], [7], [8], [7]]
Number of zeros is 0
Number of ones is 0
Number of twos is 0
Number of threes is 0
Number of fours is 0
Number of fives is 0
Number of sixes is 0
Number of sevens is 0
Number of eights is 0
Number of nines is 0
Process finished with exit code 0
Upvotes: 0
Views: 539
Reputation: 4186
>>> import collections, random
>>> nums = [random.randint(0,9) for i in range(10)]
>>> nums
[5, 9, 7, 4, 5, 3, 8, 1, 2, 1]
>>> counts = collections.Counter(nums)
>>> counts
Counter({1: 2, 5: 2, 2: 1, 3: 1, 4: 1, 7: 1, 8: 1, 9: 1})
>>> counts[1]
2
>>> counts[6]
0
Upvotes: 0
Reputation: 103467
Notice that your rand
list ends up containing a bunch of single element lists:
[[8], [6], [1], [8], [7], [0], [4], [7], [8], [7]]
That's because you wrap each entry in a list here:
int = [random.randint(0, 9)]
When you count the number of 0
s (for example) in the list, the answer is 0
because the list only contains instances of [0]
, not 0
.
Try this instead:
int = random.randint(0, 9)
Then your rand
list will look more like this:
[8, 6, 1, 8, 7, 0, 4, 7, 8, 7]
And your counting will work properly.
Upvotes: 2