python - 生成具有特定位数和 sum_of_digits 的随机数 (Python 3.8)

标签 python

我想生成一个具有特定数量的数字(由用户指定)的随机数,并且这些数字应该具有由用户指定的特定总和。我尝试将变量分配给命令random.randint(x,y),然后检查len()sum()如果该变量等于用户指定的变量,但它没有产生有用的结果。我尝试过的代码看起来像这样:

required_length = input()
required_sum = input()
z = random.randint(0 , 99999)
number = z
length = len(z)
sum1 = sum(int(digit) for digit in str(number))
if length == required_length and sum1 == required_sum:
     print(z)

如果我不够具体,为了帮助您,假设我想生成一个应该有 7 位数字的数字,并且这 7 位数字的总和应该是 7强>。这些随机数之一可能是 1121101。我希望这个示例有所帮助。

很快再见,非常感谢您的帮助。

最佳答案

简单的解决方案

您可以创建一个可以生成的数字列表,然后使用random.choice()函数从列表中选择1个元素。

import random

n = int(input("Amount of digits: "))
x = int(input("Sum of digits: "))
numbers = [num for num in range(10 ** (n - 1), 10 ** n) if sum(map(int, str(num))) == x]
print(random.choice(numbers))

快速解决方案

import random

t = []

def f(s, i):
    r = sum(map(int, s))
    if i == n:
        if r == x:
            t.append(s)
    else:
        for q in range(10) if len(s) else range(1, 10):
            if r + q <= x:
                f(s + str(q), i + 1)

n = int(input("Amount of digits: "))
x = int(input("Sum of digits: "))

f("", 0)
print(random.choice(t))

关于python - 生成具有特定位数和 sum_of_digits 的随机数 (Python 3.8),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70234243/

相关文章:

c# - 在 Ironpython 中安装 PsychoPy 作为第三方包

python - 需要将特定的列集转换为行,并将其余列转换为重复值

python - 操作系统错误: port/proto not found in for loop

python - 如何创建具有多种功能的 OpenAI Gym 观察空间

python - 更改 *splat 和 **splatty-splat 运算符对我的对象执行的操作

python - 根据长度和交集从列表列表中选择元素

python - 将Word文件与python-docx合并并添加分页符

Python - 将 Visual Studio 项目转换为具有所有依赖项的 Docker 镜像

python - 如何在递归函数中控制函数调用的次数。即递归函数调用自身的次数

python - 以列表为值python的二维字典