gpt4 book ai didi

python - 仅生成具有特定数字的随机数

转载 作者:行者123 更新时间:2023-12-04 00:17:04 25 4
gpt4 key购买 nike

如何从一组特定的数字生成随机数?例如,
我想从 1-100,000 范围内生成数字,这样每个数字只有奇数位(例如:111135119711等)

使用我尝试过的随机模块:

import random

rand = random.randint([1, 3, 5, 7, 9])

有什么有效的方法吗?
谢谢。

最佳答案

一种方法是定义一个概率列表,从中进行抽样,但要记住随机抽样一个数字的可能性应该有多大。由于两位数的数量是一位数的十倍,我们需要按照这个逻辑来设置这些样本大小的权重。

按照这个推理,我们可以使用 numpy.random.choice,它允许按照概率分布从列表中抽样:

from numpy.random import choice

odds = ['1','3','5','7','9']

n_digits = 5 # up to 99999 for ex
range_digits = list(range(1,n_digits))

weights = [5**i for i in range_digits]
weights_sum = sum(weights)
probs = [i/weights_sum for i in weights]

sizes = choice(range_digits,size=n,p=probs)
[int(''.join(choice(odds,size))) for size in sizes]
# [3151, 3333, 1117, 7577, 1955, 1793, 5713, 1595, 5195, 935]

让我们检查生成的 10_000 个样本的分布:

from collections import Counter

sizes = choice(range_digits,size=10_000,p=probs)
out = [int(''.join(choice(odds,size))) for size in sizes]

Counter(len(str(i)) for i in out)
# Counter({4: 8099, 3: 1534, 2: 304, 1: 63})

关于python - 仅生成具有特定数字的随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62931500/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com