首页 > 解决方案 > 抽一个数

问题描述

获得一个号码30次需要多长时间。

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")

标签: python

解决方案


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

推荐阅读