简体   繁体   English

如何在Python中使用if语句生成随机数?

[英]How to generate random numbers with if-statement in Python?

I would like to generate random numbers with a specific restriction using python. 我想使用python生成具有特定限制的随机数。 The code should do the following: 该代码应执行以下操作:

If an entered number is: 如果输入的数字是:

0, then generate 0 random non-recurrent numbers 0,然后生成0个随机非经常性数字
<1, then generate 1 random non-recurrent numbers <1,然后生成1个随机非经常性数字
<9, then generate 2 random non-recurrent numbers <9,然后生成2个随机非经常性数字
<15, then generate 3 random non-recurrent numbers <15,然后生成3个随机非经常性数字
<26, then generate 5 random non-recurrent numbers <26,然后生成5个随机非经常性数字
<51, then generate 8 random non-recurrent numbers <51,然后生成8个随机非经常性数字
<91, then generate 13 random non-recurrent numbers <91,然后生成13个随机非经常性数字
<151, then generate 20 random non-recurrent numbers <151,然后生成20个随机非经常性数字
<281, then generate 32 random non-recurrent numbers <281,然后生成32个随机非经常性数字

The value of the random numbers should be limited by the value of the entered number. 随机数的值应受输入数字的值的限制。 So if a 75 is entered, then the code should generate 13 random numbers with being 75 the highest value of the 13 numbers. 因此,如果输入75,则代码应生成13个随机数,其中13个数字中的最大值为75。 75 doesn't have to be the actual highest number, just in terms of max value. 75不一定是实际的最高数字,仅就最大值而言。

My guess was to use numpy. 我的猜测是使用numpy。 Here is what I got until now (with an users help). 这是到目前为止我得到的(在用户帮助下)。

num_files=[0,1,9,...] 
num_nums=[0,1,2,3,5,...]
for zipp in zip(num_files,num_nums)
if len(docx_files)<zipp[0]:
list_of_rands=np.random.choice(len(docx_files)+1, 
zipp[1],replace=False)

Any ideas or more starting points? 有什么想法或更多起点吗?

Here's one way of doing it. 这是一种方法。 Just zip the lists of numbers and the cutoffs, and check if the number input (the variable number in the code below) is above the cutoff. 只需压缩数字和截止值的列表,然后检查输入的数字(下面代码中的变量number )是否在截止值以上。 Note that this doesn't handle the case of numbers larger than 281, since I'm not sure what's supposed to happen there based on your description. 请注意,这不能处理大于281的数字,因为根据您的描述我不确定在那里会发生什么。

import numpy as np

number = 134
parameters = zip([9, 15, 26, 51, 91, 151], [3, 5, 8, 13, 20, 32])    
nums = 2

for item in parameters:
    if number > item[0]:
        nums = item[1]

np.random.choice(number, nums)

You can avoid a many-branched if-elif-else using np.searchsorted : 您可以使用np.searchsorted避免多分支if-elif-else

import numpy as np

def generate(x):
    boundaries = np.array([1, 2, 9, 15, 26, 51, 91, 151, 281])
    numbers = np.array([0, 1, 2, 3, 5, 8, 13, 20, 32])
    return [np.random.choice(j, n, False)+1 if j else np.array([], np.int64)
            for j, n in np.broadcast(x, numbers[boundaries.searchsorted(x, 'right')])]

# demo
from pprint import pprint
# single value
pprint(generate(17))
# multiple values in one go
pprint(generate([19, 75, 3, 1, 2, 0, 8, 9]))
# interactive
i = int(input('Enter number: '))
pprint(generate(i))

Sample output: 样本输出:

[array([ 9,  1, 14,  4, 12])]
[array([ 8, 12,  6, 17,  4]),
 array([17, 29,  2, 20, 16, 37, 36, 13, 34, 58, 49, 72, 41]),
 array([1, 3]),
 array([1]),
 array([2, 1]),
 array([], dtype=int64),
 array([1, 8]),
 array([3, 2, 6])]
Enter number: 280
[array([184,  73,  80, 280, 254, 164, 192, 145, 176,  29,  58, 251,  37,
       107,   5,  51,   7, 128, 142, 125, 135,  87, 259,  83, 260,  10,
       108, 210,   8,  36, 181,  64])]

I don't know how to implement it in your code but with this code you then you get the randoms: 我不知道如何在您的代码中实现它,但是通过此代码,您便获得了随机数:

import random

x = 51

if x < 26:
   ar_Random = [None]*5
   for i in range(0, 6):
      ar_Random[i] = random.randint(startNumOfRandom, stopNumOfRandom)
elif x < 51:
   ar_Random = [None]*8
   for i in range (0,9):
       ar_Random[i] = random.randint(startNumOfRandom, stopNumOfRandom)
...

I'm not sure how you're mapping the length to the input but this is how you generate N random numbers with a maximum using Numpy. 我不确定如何将长度映射到输入,但这是使用Numpy生成N个随机数最大的方式。

import numpy as np

//set entered_num and desired_length to whatever you want
random_nums = np.random.randint(entered_num, size = desired_length)
import random

Starting_Number = int(input())

if Starting_Number < 26:
    print(random.sample(range(1, 26), 5))

elif Starting_Number < 51:
    print(random.sample(range(1, 51), 8))

elif Starting_Number < 91:
    print(random.sample(range(1, 91), 13))

Here you go!!! 干得好!!!

random.sample is the module you are looking for. random.sample是您正在寻找的模块。

Have a good one! 祝你有个好的一天!

You could define a function using a dictionary with ranges as keys and number of random numbers as values: 您可以使用字典定义函数,其范围作为键,随机数作为值:

import random

def rand_nums(input_num):
    d = {26: 5, 51: 8, 91: 13}

    for k, v in d.items():
        if input_num in range(k):
            nums = random.sample(range(k+1), v)
            return nums



print(rand_nums(20))
print(rand_nums(50))
print(rand_nums(88))

[14, 23, 11, 9, 5]
[9, 49, 23, 16, 8, 50, 47, 33]
[20, 16, 28, 77, 21, 87, 85, 82, 10, 47, 43, 90, 57]
>>> 

How about: 怎么样:

def gen_rand_array(n):
    mapping = np.array([[1,1],
                        [26,5],
                        [51,8],
                        [91,13]])
    k = mapping[np.max(np.where(n > mapping[:,0])),1]
    return np.random.choice(n+1,k)

Example: 例:

>>> gen_rand_array(27)
array([ 0, 21, 26, 25, 23])
>>> gen_rand_array(27)
array([21,  5, 10,  3, 13])
>>> gen_rand_array(57)
array([30, 26, 50, 31, 44, 51, 39, 13])
>>> gen_rand_array(57)
array([21, 18, 35,  8, 13, 13, 20,  3])

Here's a screen shot putting it all together: 这是将所有内容组合在一起的屏幕截图:

在此处输入图片说明

Explanation: 说明:

The line k = mapping[np.max(np.where(n > mapping[:,0])),1] is just finding the number of random values needed from the array mapping . k = mapping[np.max(np.where(n > mapping[:,0])),1]只是从数组mapping找到所需的随机值数量。 n > mapping[:,0] return a boolean array whose values will be True for all the numbers smaller then n , False otherwise. n > mapping[:,0]返回一个布尔数组,对于所有小于n的数字,其值为True ,否则为False np.where(...) will return the indexes of the elements of the array that are true. np.where(...)将返回为真的数组元素的索引。 Since the values in the first column of mapping (ie mapping[:,0] ) are ascending, we can find the index of the largest one that is less than n be calling np.max(...) . 由于mapping的第一列中的值(即mapping[:,0] )正在递增,因此调用np.max(...)可以找到小于n的最大索引。 Finally we want the corresponding value from the second column which is why we pass the result of that as an index to mapping again ie mapping[...,1] where the 1 is for the second column. 最后,我们需要第二列中的相应值,这就是为什么我们将其结果作为索引再次传递到映射的原因,即mapping[...,1]其中1代表第二列。

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

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