简体   繁体   English

随机数生成器仅打印一个数字

[英]Random Number Generator Only Printing One Number

This is the code I have so far: 这是我到目前为止的代码:

 from quick_pick import quick_pick
    def main():
     LIMIT = 67
     number = 9
     list_1 = []*number
     quick_pick(number, LIMIT, list_1)
     print (list_1)
     main()

import random
def quick_pick(n,limit,lottery):
    main_count = 0
    while main_count <n:
        lotto_numbers = random.randint(1, limit)
        if lotto_numbers not in lottery:
            lottery.append(lotto_numbers)
            main_count += 1
            return (lottery * n)

but when I run it I get this: [21] 但是当我运行它时,我得到了: [21]

Im not sure how to get all 9 numbers to show up in the list so I can print it. 林不知道如何让所有9个数字显示在列表中,以便我可以打印它。 If someone could help it would be appreciated as this is for part of my assignment and I need it to do the rest of it. 如果有人可以帮助,将不胜感激,因为这是我的任务之一,我需要它来完成其余的工作。

You can use random.sample to pick the numbers: 您可以使用random.sample来选择数字:

limit = 67
n = 9
print(random.sample(range(1, limit + 1), n)) # [49, 32, 66, 57, 25, 9, 22, 4, 48]

Fix you indentation, lose the * n , and viola(!), your code works: 解决您的缩进问题,丢失* n和viola(!),您的代码有效:

def quick_pick(n,limit,lottery):
    main_count = 0
    while main_count <n:
        lotto_numbers = random.randint(1, limit)
        if lotto_numbers not in lottery:
            lottery.append(lotto_numbers)
            main_count += 1
    return lottery

>>> quick_pick(number,LIMIT,list_1)
[44, 43, 62, 13, 11, 25, 36, 29, 15]

The problem was, as you can see, the fact that you return after finding the first number to add to your lottery . 如您所见,问题是,您在找到第一个要添加到lottery号码后便return了。 You need to wait until it is filled up. 您需要等待直到填满。 Also multiplying by n (9) doesn't make much sense. 同样,乘以n (9)也没有多大意义。

Another way to get random numbers following some particular distribution is to use the probability distributions directly.. 获取遵循某些特定分布的随机数的另一种方法是直接使用概率分布。

Example: 例:

import numpy as np

nums = np.random.uniform(-1, 1, (100, 2))

This will generate a hundred 2-dimensional points in the range (-1, 1) from the underlying uniform distribution (all the numbers in the range have the same probability of being picked). 这将从基础均匀分布中生成范围(-1,1)内的一百个二维点(范围内的所有数字具有相同的被拾取概率)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM