如何生成不同的随机数?

编程入门 行业动态 更新时间:2024-10-27 14:30:27
本文介绍了如何生成不同的随机数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

可能重复: 随机选择N个项目

Possible Duplicate: pick N items at random

我需要生成1到49之间的6个随机数,但是它们不能相同.我知道如何使它们随机化,但我不确定如何确保它们不同.

I need to generate 6 random numbers between 1 and 49, but they cannot be the same. I know how to do make them random, I just am not sure how to ensure that they are different.

工作表建议显示每个数字并将其设置为零,但我看不出有什么帮助.

The worksheet recommends displaying each number and setting it to zero, but I don't see how that would help.

任何建议都将不胜感激.

Any advice is greatly appreciated.

推荐答案

您可以使用 random.sample :

You can use random.sample:

>>> random.sample(xrange(1,50), 6) [26, 39, 36, 46, 37, 1]

工作表建议显示每个数字并将其设置为零,但我看不出有什么帮助."

假设这是一项任务,并且您需要自己实施抽样,则可以看看如何实现random.sample .它确实提供了很多信息,但是对于您的需求而言可能太复杂了,因为代码还确保了所有子切片也将是有效的随机样本.为了提高效率,它还根据人口规模使用了不同的方法.

Assuming this is an assignment and you need to implement the sampling yourself, you could take a look at how random.sample is implemented. It's really informative, but may be too complicated for your needs since the code also ensures that all sub-slices will also be valid random sample. For efficiency, it also uses different approaches depending on the population size.

对于工作表,我认为它假设您从1到49的数字列表开始,并建议您将选择的数字替换为0,以便在重新选择时可以跳过.以下是一些伪代码,可以帮助您入门:

As for the worksheet, I believe it assumes you're starting off with a list of numbers from 1 to 49 and suggests that you replace numbers that you're selected with 0 so there can be skipped if reselected. Here's some pseudo code to get you started:

population = range(1, 50) # list of numbers from 1 to 49 sample = [] until we get 6 samples: index = a random number from 0 to 48 # look up random.randint() if population[index] is not 0: # if we found an unmarked value append population[index] to sample set population[index] = 0 # mark selected

如果您想尝试一些不同的方法,则可以考虑其他许多方法,例如将列表随机化然后截断,或者某种形式的储层采样.

If you wish to attempt something different, there are many other approaches to consider e.g. randomising the list then truncating, or some form of reservoir sampling.

祝您工作顺利.

更多推荐

如何生成不同的随机数?

本文发布于:2023-10-28 23:05:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1538025.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:随机数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!