【问题标题】:How to generate random numbers of unique modulus values in python如何在python中生成唯一模值的随机数
【发布时间】:2018-09-23 10:13:21
【问题描述】:
import random
value = 1000
a = []
i = 0
b = [None] * 16
print('value = ',1000)
for x in range(value):
    a.append(x)
    random.Random(4).shuffle(a)
print(a)
for x in range(16):
    b[x] = a[x]
print(b)

此代码生成 16 个随机数,范围为 1000。但是如何在 python 中生成具有从 1 到 26 不同模值的数字呢?

考虑数值示例

随机得到的值为: 184,15,106,8,93,150,210,144,271,365,65,60,385,164,349,405 当我们使用所有这些数字执行mod 26 操作时,我们得到 0,15,2,8,15,20,2,14,11,1,13,8,21,8,11,15分别

这里的数字15,8,11,2 是重复的。所以我想消除这种重复。为此,我想在执行mod 26 操作时生成具有不同值的随机数。

【问题讨论】:

  • 什么是“唯一模值”?
  • 唯一模数意味着为每个随机选择的数字计算的模值(例如 421 mod 26 )应该是不同的,或者如上所述选择 16 个具有不同模值的随机数,从 1 到 26。

标签: python random modulus


【解决方案1】:

假设你想找到以5为模的16数为4,最大值不大于1000

Numpy 解决方案

def choose_random(max_limit=1000, modulo=5, value=4, size=16):
    x_max = (max_limit - value) // modulo
    if (max_limit - value) % modulo != 0:
        x_max += 1
    x = np.arange(x_max)
    y = x * modulo + value
    return np.random.choice(y, size=size, replace=True)

print(choose_random())
Out: [309 939 449 219 639 614 779 549 189   4 729 629 939 159 934 654] 

更简单的 Numpy 解决方案

def choose_random(max_limit=1000, modulo=5, value=4, size=16):
    y = np.arange(value, max_limit, value)
    return np.random.choice(y, size=size, replace=True)

如果你想要 n 不同的模 modulo

def distinct_modulo(n, modulo):
    if n > modulo:
        raise Exception("Can't return more than {0} distinct values!".format(modulo))
    return np.random.choice(modulo, size=n, replace=False)

您只需返回 n 范围内的不同值 [0, modulo - 1]

distinct_modulo(n=16, modulo=26)
Out: [ 0, 19, 23,  5,  6, 25, 21, 22, 10, 16, 12, 14, 20, 15,  1,  8]

非 Numpy 解决方案

import random
def distinct_modulo(n, modulo):
    if n > modulo:
        raise Exception("Can't return more than {0} distinct values!".format(modulo))
    return random.sample(range(modulo), n)

distinct_modulo(n=16, modulo=26)     
Out: [14, 17, 13, 10, 1, 6, 0, 20, 2, 21, 4, 19, 9, 24, 25, 16]                                     

【讨论】:

  • 所选数字的计算模块值应该不同,或者每个模块值应该是唯一的,并且模块值可以在1到26的范围内
  • 如果你能在上面给我们一个数值例子就更好了
  • 我在问题中添加了一个简单的数字解释。希望你能理解我的问题。
  • 这里的数字也在你的输出中重复。你能在不使用 numpy 的情况下这样做吗?
  • 最后一个代码中的错误是replace=True必须是replace=False。还添加了非 numpy 解决方案
【解决方案2】:

你可以 随机导入 随机样本(范围(10000),1000) 这将生成 1000 个随机数

例如获取 10,000 范围内的 10 个随机数

随机样本(范围(10000),10) [3339、2845、9485、2601、3569、1332、7123、4861、9893、9483]

【讨论】:

    猜你喜欢
    • 2018-06-23
    • 1970-01-01
    • 1970-01-01
    • 2019-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-05
    相关资源
    最近更新 更多