简体   繁体   English

Python 随机模块:如何生成包含特定数字的随机数?

[英]Python random module: How can I generate a random number which includes certain digits?

I am trying to generate a random number in Python, but I need it to include certain digits.我正在尝试在 Python 中生成一个随机数,但我需要它包含某些数字。

Let's say the range I want for it is between 100000 and 999999, so I want it to be in that range but also include digits like 1, 4, and 5.假设我想要的范围在 100000 到 999999 之间,所以我希望它在该范围内,但也包括 1、4 和 5 等数字。

Is there a way to do this?有没有办法做到这一点?

you can build the number digit by digit您可以逐位构建数字

>>> import random
>>> def fun(required=(),size=6):
        result = list(required)
        n = size-len(result)
        result.extend( random.randint(0,10) for _ in range(n)) # fill in the remaining digits
        random.shuffle(result) 
        assert any(result) #make sure that there is at least one non zero digit
        while not result[0]: #make sure that the first digit is non zero so the resulting number be of the required size
            random.shuffle(result)
        return int("".join(map(str,result)))

>>> fun([1,4,5])
471505
>>> fun([1,4,5])
457310
>>> fun([1,4,5])
912457
>>> fun([1,4,5])
542961
>>> fun([1,4,5])
145079
>>> 

The obvious answer to me is brute force.对我来说,显而易见的答案是蛮力。

import random

def check(digits,number):
    passes = True
    number = str(number)
    for k in digits:
        if not str(k) in number:
            passes = False
            break
    return passes

def genRandom(digits):
    minimum = 100000
    maximum = 1000000
    r = minimum+int(random.random()*(maximum-minimum))
    while not check(digits,r):
        r = minimum + int(random.random() * (maximum - minimum))
    return r

print(genRandom([1,4,5]))

From reading comments I've seen 3 other solid suggestions.从阅读评论中,我看到了其他 3 个可靠的建议。 First randomly replace digits with the needed values.首先用需要的值随机替换数字。 Which sounds simple but requires some ugliness to avoid replacing digits that you have designated as necessary and to avoid index errors when potentially getting digits past the end of your number.这听起来很简单,但需要一些丑陋,以避免替换您指定为必要的数字,并避免在可能使数字超过您的数字末尾时出现索引错误。

import random

def genRandom(digits):
    digits = [str(k) for k in digits]
    minimum = 100000
    maximum = 1000000
    r = str(minimum+int(random.random()*(maximum-minimum)))
    for k in digits:
        while not k in r:
            i = int(random.random()*len(r))
            if r[i] in digits:
                if i==len(r)-1:
                    if not r[i] in r[0:i]:
                        continue
                elif not r[i] in r[0:i]+r[i+1:]:
                    continue
            if i==len(r)-1:
                r=r[0:i]+k
            else:
                r=r[0:i]+k+r[i+1:]
    return(r)

print(genRandom([1,4,5]))

The third option of generating a list of acceptable numbers and picking from that was well stated by enke in their answer. enke 在他们的回答中很好地说明了生成可接受数字列表并从中挑选的第三个选项。 While this is a nice looking answer it is actually substantially more intensive in terms of runtime for a single call.虽然这是一个看起来不错的答案,但它实际上在单个调用的运行时间方面更加密集。

The best answer in my opinion is Copperfield's build the number digit by digit.我认为最好的答案是科波菲尔逐位构建数字。

Create a set of required numbers as strings, and create a list of valid numbers where the required integers appear using set.intersection on string representation of numbers.创建一组所需的数字作为字符串,并创建一个有效数字列表,其中所需的整数出现在数字的字符串表示上使用set.intersection Then use random.choice to select a random number from the valid list:然后使用random.choice到 select 一个来自有效列表的随机数:

import random
required = set(map(str, [1,4,5]))
valid_numbers = [int(num) for num in map(str, range(100000,1000000)) if required.intersection(num)]
random.choice(valid_numbers)

The easiest way I can think of doing this is by adding a few extra numbers to the beginning or end of your range and then mapping those extra numbers to the ones that you want.我能想到的最简单的方法是在范围的开头或结尾添加一些额外的数字,然后将这些额外的数字映射到您想要的数字。 Using your example of 1 , 4 , and 5 this example shows how that would work.使用您的145示例,此示例显示了它是如何工作的。

import random

num = random.randint(99997, 999999)
if num == 99997:
  num = 1
elif num == 99998:
  num = 4
elif num == 99999:
  num = 5
print(num)

I Got it working doing this我得到它的工作做这个

import random, string
from random import randrange

a_list = [1,4,5]
A = random.choice( a_list)  #these are your 3 numbers
B = randrange(100000, 9999999) # your own chosen range
result= f'({A})-{B}'
print(result)
Now each time you print you get answer like:现在每次打印时都会得到如下答案:
(4)-1760765
(5)-6229821
(1)-3093513
(1)-1381767
(5)-2117529

( don't forget to validate my answer if it helps, thank you ) (如果有帮助别忘了验证我的回答,谢谢)
import random

random.randint(100000, 999999)

If I'm understanding your question correctly this should be what you want如果我正确理解您的问题,这应该是您想要的

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

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