python - 抽一个数
问题描述
获得一个号码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")
解决方案
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
推荐阅读
- macros - 如何在 sbcl common lisp 的 let 绑定中定义(defmacro)宏?
- c - 如何在没有 GPU 的情况下在 Arm 上加速 Gtk2+ 的 Cairo 绘画速度
- windows - 如何在 .bat 文件的“for”命令中格式化 Tesseract-OCR 语言设置
- java - 如何通过摆脱冗余来优化下面的代码?
- twitter-bootstrap - 导航切换向下滚动超过该部分的开头
- eclipse - 将 ISO20022 E-Repository 导入 Eclipse 的问题
- ruby - 为什么有人会将 ruby-saml gem 请求/响应的证书签名设置为 false?
- java - 无法删除二叉树中的节点
- php - RegEx 模式不起作用:在 PHP 中匹配域名最后一部分之后的所有内容
- python - 烧瓶 gunicorn 到 API 端点映射可能吗?