仅生成具有特定数字的随机数 [英] Generate random numbers only with specific digits

查看:68
本文介绍了仅生成具有特定数字的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从一组特定的数字生成随机数?例如,
我想生成 1-100,000 范围内的数字,这样每个数字都只有奇数位(例如:1111351>19711 等等.)

使用我尝试过的随机模块:

随机导入rand = random.randint([1, 3, 5, 7, 9])

有什么有效的方法吗?
谢谢.

解决方案

这是一个使用列表推导式的解决方案:

<预><代码>>>>random.sample([i for i in range(1,100_001) if all([int(x)%2==1 for x in str(i)])], 4)[3115、75359、53159、31771]


正如下面的评论所指出的,上面的代码变得越来越低效,数字越大,因为所有数字都被检查,如果每个数字都只包含奇数.这包括偶数.

如果我们添加另一个过滤器来首先删除所有偶数,我们会将进行的比较数量减少大约三分之一.

以下是两者之间的快速比较:

导入日期时间随机导入定义计时器(var):def 包装器(*args, **kwargs):开始 = datetime.datetime.now()结果 = var()打印(f经过时间:{datetime.datetime.now()-开始}")返回结果返回包装器@定时器def allNumbers():return random.sample([i for i in range(1, 1_000_001) if all([int(x) % 2 == 1 for x in str(i)])], 4)@定时器定义奇数():return random.sample([i for i in [x for x in range(1, 1_000_001) if x % 2 == 1] if all([int(x) % 2 == 1 for x in str(i)])], 4)打印(呼叫所有号码:")打印(所有数字())打印(调用奇数:")打印(奇数())

输出:

调用 allNumbers:经过时间:0:00:05.119071[153539、771197、199379、751557]调用奇数:经过时间:0:00:02.978188[951919、1399、199515、791393]

How do I generate a random number from a specific set of digits? For example,
I want to generate numbers from the range 1-100,000 such that every number has only odd digits (for example: 111, 1351, 19711 etc..)

Using the random module I tried:

import random

rand = random.randint([1, 3, 5, 7, 9]) 

Is there any efficient way of doing it?
Thank you.

解决方案

Here is a solution using list-comprehension:

>>> random.sample([i for i in range(1,100_001) if all([int(x)%2==1 for x in str(i)])], 4)
[3115, 75359, 53159, 31771]


As pointed out in the comments below, the above code becomes more and more inefficient the larger the numbers get, due to all numbers being checked if each of them includes only odd-numbers. That includes numbers that are even.

IF we add another filter to first remove all even-numbers we reduce the amounts of comparisons that are being made by about a third.

Here is a quick comparison between the two:

import datetime
import random

def timer(var):
    def wrapper(*args, **kwargs):
        start = datetime.datetime.now()
        result = var()
        print(f"Elapsed time: {datetime.datetime.now()-start}")
        return result
    return wrapper

@timer
def allNumbers():
    return random.sample([i for i in range(1, 1_000_001) if all([int(x) % 2 == 1 for x in str(i)])], 4)

@timer
def oddNumbers():
    return random.sample([i for i in [x for x in range(1, 1_000_001) if x % 2 == 1] if all([int(x) % 2 == 1 for x in str(i)])], 4)

print("Calling allNumbers:")
print(allNumbers())
print("Calling oddNumbers:")
print(oddNumbers())

Output:

Calling allNumbers:
Elapsed time: 0:00:05.119071
[153539, 771197, 199379, 751557]
Calling oddNumbers:
Elapsed time: 0:00:02.978188
[951919, 1399, 199515, 791393]

这篇关于仅生成具有特定数字的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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