如何在Python中不重复地生成一定范围的随机数 [英] How to generate a range of random numbers in python without repetition

查看:94
本文介绍了如何在Python中不重复地生成一定范围的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想生成(0 ..."MAX")范围内的随机数.我想做一个循环,这样每次循环时都会生成一个新的唯一随机数(不应重复).循环将总共持续"MAX"次.总共应产生"MAX"个随机数.排序时,值应为0 ..."MAX";没有重复.

I would like to generate random numbers in the range (0..."MAX"). I would like to make a loop such that every time going through the loop a new unique random number is generated (should not repeat). The loop will continue a total of "MAX" times. There should be "MAX" number of random numbers generated in total. When sorted, the values should be 0..."MAX"; no repetition.

限制: -假设MAX比int大得多. (没有内存可将所有数字排列存储在内存中)

Restrictions: - Assume MAX is much larger than int. (no memory to store all number permutations in memory)

我建议的解决方案: 如果我将生成器的种子从0 ... MAX设为种子,那将允许我按照以下功能打印0到MAX之间的每个唯一数字?假设没有空间来存储所有数字并对其进行改组.

My proposed solution: If I seed the generator from 0...MAX would that allow me to print every unique number between 0 and MAX as in the below function? Assume there's no space to store all numbers and shuffling them.

for x in range (0, MAX):
    random.seed(x)
    num=random.randint(0, MAX)
    print("seed = ",x, "    random number = ", num)

如果上面的答案是肯定的,那么这一代将是可逆的(我可以从随机数中获得种子)吗?在那种情况下,如果种子(密钥)和范围是相同的长度,这将被视为一种分组密码吗?

If the answer for the above is yes then would this generation be reversible (can i get the seed from the random number)? In which case would this be considered a kind of block cipher that is if the seed (key) and the range is the same length?

推荐答案

您可以这样做:

input = set()
for i in range(MAX):
    input.add(random.randrange(x,y))
print input

在x和y范围内,它将选择一些随机值.无重复意味着您可以使用set.所以我要添加这些值来设置.

with in the range of x and y it will select some random values. W/o repetition means you can use set. so i am adding those values to set.

只需尝试一下.

这篇关于如何在Python中不重复地生成一定范围的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆