-1

how long it takes to get one number 30 times.

import random
import time

start = time.time()

for i in range(30):
    number = random.randint(1, 1000000)
    print(number)

end = time.time()
print("time =", (end - start), "s")
  • What does "get to one number 30 times" mean? Same with "I have a problem drawing a specific number e.g. 5"? The task you are trying to accomplish is not clear. Are you asking how long it takes draw a number randomly from a set 30 times? If so how do you know what number you should be counting? Or is it any number? None of these details are clear to me – sedavidw Feb 09 '21 at 04:01
  • If you are using a range of 30, you will get 30 random numbers only. Getting 30 same numbers in 30 range is impossible. You need to extend the loop for infinite range and a condition to stop when you reach a number 30 times. – T.kowshik Yedida Feb 09 '21 at 04:01
  • Please describe your problem in details. – Klaus D. Feb 09 '21 at 04:02

1 Answers1

1

You need to extend your loop to continue until your condition has been met, you'll almost never hit the same number 30 times on your first 30 tries. A dictionary will let you keep track how often you see each number

import random
import time
from collections import defaultdict

counts = defaultdict(int)

start = time.time()

while True:
    number = random.randint(1, 1000000)
    counts[number] += 1
    if counts[number] == 30:
        break

end = time.time()

print("time =", (end - start), "s")
print("Number found 30 times", number)

Sample output

time = 8.579060077667236 s
Number found 30 times 465175
sedavidw
  • 11,116
  • 13
  • 61
  • 95
  • 1
    [Follow up questions](https://meta.stackoverflow.com/questions/266767/what-is-the-the-best-way-to-ask-follow-up-questions) are bad practice on stack overflow. If you have a new question you should ask it as a new question. That being said I'd encourage you to look up about [thread safety in python's dictionary](https://stackoverflow.com/questions/6953351/thread-safety-in-pythons-dictionary). – sedavidw Feb 09 '21 at 04:26