如何生成满足某些条件的三个随机整数? [英] How can I generate three random integers that satisfy some condition?

查看:52
本文介绍了如何生成满足某些条件的三个随机整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是编程的初学者,正在寻找如何生成满足条件的三个整数的好主意.

I'm a beginner in programming and I'm looking for a nice idea how to generate three integers that satisfy a condition.

示例:

给定 n = 30,我们被要求生成三个整数 a、b 和 c,所以 7*a + 5*b + 3*c =n.我尝试使用 for 循环,但它花费了太多时间,而且我的最大测试时间为 1000 毫秒.

We are given n = 30, and we've been asked to generate three integers a, b and c, so that 7*a + 5*b + 3*c = n. I tried to use for loops, but it takes too much time and I have a maximum testing time of 1000 ms.

我使用的是 Python 3.

I'm using Python 3.

我的尝试:

x = int(input())
c = []
k = []
w = []
for i in range(x):
    for j in range(x):
        for h in range(x):
           if 7*i + 5*j + 3*h = x:
              c.append(i)
              k.append(j)
              w.append(h)
if len(c) == len(k) == len(w) 
    print(-1)
else: 
    print(str(k[0]) + ' ' + str(c[0]) + ' ' + str(w[0]))

推荐答案

import numpy as np


def generate_answer(n: int, low_limit:int, high_limit: int):
    while True:
        a = np.random.randint(low_limit, high_limit + 1, 1)[0]
        b = np.random.randint(low_limit, high_limit + 1, 1)[0]
        c = (n - 7 * a - 5 * b) / 3.0
        if int(c) == c and low_limit <= c <= high_limit:
            break

    return a, b, int(c)


if __name__ == "__main__":
    n = 30
    ans = generate_answer(low_limit=-5, high_limit=50, n=n)
    assert ans[0] * 7 + ans[1] * 5 + ans[2] * 3 == n
    print(ans)

如果您选择数字 a、b、c 中的两个,您就会知道第三个.在这种情况下,我将 a、b 的整数随机化,然后通过 c = (n - 7 * a - 5 * b)/3.0 找到 c.

If you select two of the numbers a, b, c, you know the third. In this case, I randomize ints for a, b, and I find c by c = (n - 7 * a - 5 * b) / 3.0.

确保 c 是一个整数,并且在允许的范围内,我们就完成了.

Make sure c is an integer, and in the allowed limits, and we are done.

如果不是,再次随机化.

If it is not, randomize again.

如果你想产生所有的可能性,

If you want to generate all possibilities,

def generate_all_answers(n: int, low_limit:int, high_limit: int):
    results = []
    for a in range(low_limit, high_limit + 1):
        for b in range(low_limit, high_limit + 1):
            c = (n - 7 * a - 5 * b) / 3.0
            if int(c) == c and low_limit <= c <= high_limit:
                results.append((a, b, int(c)))

    return results

这篇关于如何生成满足某些条件的三个随机整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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