1

I have a program which generates random numbers from -10 to 10. My task is to count how many elements from 1 to 5 are in this massive. the problem is that I can't use functions like counter or others because TypeError: 'int' object is not iterable . Which functions can i use to fix it?

import random

for i in range(51):
    a = random.randint(-10, 10)
print(a)
solid.py
  • 2,782
  • 5
  • 23
  • 30
  • 1
    "the problem is that I can't use functions like counter or others because `TypeError: 'int' object is not iterable`." ----> You absolutely **can** use Counter. Apparently you tried to use Counter but there was an error in your code. Since you didn't post your code, we don't know what's wrong with your code. – Stef Oct 05 '20 at 10:13

2 Answers2

2

You absolutely can use collections.Counter for this:

import random
import collections
c = collections.Counter(random.randint(-10, 11) for i in range(51))
print(c)
# Counter({-9: 7, 10: 7, -5: 5, 8: 3, 1: 3, -10: 3, -4: 3, -7: 3, 5: 3, 0: 3, -3: 2, 6: 2, 4: 2, 9: 2, 3: 1, -6: 1, 2: 1})
n = sum(c[i] for i in range(1,6))  # number of elements between 1 and 5
print(n)
# 10
Stef
  • 13,242
  • 2
  • 17
  • 28
1

You could try something like this, which sums 1 if the random int is in range from 1 to 5, and this runs for 51 times. Finally, this sum is printed.

import random

print(sum(1 for i in range(51) if random.randint(-10, 11) in range(1, 5)))

The above segment is equivalent to:

import random

a = 0
for i in range(51):
    if random.randint(-10, 11) in range(1, 5):
        a += 1
print(a)
solid.py
  • 2,782
  • 5
  • 23
  • 30