[英]Generate all sets of three numbers which sum up to 12 python
I would like to generate all the tuples of three numbers which add up to 12. For example: ((12, 0, 0), (11, 1, 0))
, and so on.我想生成三个数字加起来为 12 的所有元组。例如:
((12, 0, 0), (11, 1, 0))
等等。 How would you generate this entire list in python?您将如何在 python 中生成整个列表? I tried:
我试过了:
x = []
for a in range(0, 13):
for b in range(0, 13):
for c in range(0, 13):
x.append((a, b, c))
I also tried to only append to the list if the sum was 12, but I feel like this is a very inefficient way to complete the task, because it loops over way more iterations than necessary.如果总和为 12,我还尝试仅将 append 加入列表,但我觉得这是完成任务的一种非常低效的方式,因为它循环的迭代次数比必要的多。
You can use itertools.product
for this to avoid nested loops (based on @User 12692182's answer )您可以使用
itertools.product
来避免嵌套循环(基于@User 12692182 的回答)
from itertools import product
[(a, b, 12-a-b) for a, b in product(range(13), repeat=2) if 12-a-b >=0]
Results:结果:
[(0, 0, 12), (0, 1, 11), (0, 2, 10), (0, 3, 9), (0, 4, 8), (0, 5, 7), (0, 6, 6), (0, 7, 5), (0, 8, 4), (0, 9, 3), (0, 10, 2), (0, 11, 1), (0, 12, 0), (1, 0, 11), (1, 1, 10), (1, 2, 9), (1, 3, 8), (1, 4, 7), (1, 5, 6), (1, 6, 5), (1, 7, 4), (1, 8, 3), (1, 9, 2), (1, 10, 1), (1, 11, 0), (2, 0, 10), (2, 1, 9), (2, 2, 8), (2, 3, 7), (2, 4, 6), (2, 5, 5), (2, 6, 4), (2, 7, 3), (2, 8, 2), (2, 9, 1), (2, 10, 0), (3, 0, 9), (3, 1, 8), (3, 2, 7), (3, 3, 6), (3, 4, 5), (3, 5, 4), (3, 6, 3), (3, 7, 2), (3, 8, 1), (3, 9, 0), (4, 0, 8), (4, 1, 7), (4, 2, 6), (4, 3, 5), (4, 4, 4), (4, 5, 3), (4, 6, 2), (4, 7, 1), (4, 8, 0), (5, 0, 7), (5, 1, 6), (5, 2, 5), (5, 3, 4), (5, 4, 3), (5, 5, 2), (5, 6, 1), (5, 7, 0), (6, 0, 6), (6, 1, 5), (6, 2, 4), (6, 3, 3), (6, 4, 2), (6, 5, 1), (6, 6, 0), (7, 0, 5), (7, 1, 4), (7, 2, 3), (7, 3, 2), (7, 4, 1), (7, 5, 0), (8, 0, 4), (8, 1, 3), (8, 2, 2), (8, 3, 1), (8, 4, 0), (9, 0, 3), (9, 1, 2), (9, 2, 1), (9, 3, 0), (10, 0, 2), (10, 1, 1), (10, 2, 0), (11, 0, 1), (11, 1, 0), (12, 0, 0)]
You would have to use subtraction, to avoid not going above 12, or below it.您必须使用减法,以避免超过 12 或低于 12。 First, you would use a range of 0 to 12, independent from everything else.
首先,您将使用 0 到 12 的范围,独立于其他所有内容。 Then, you would use another range, however with this one, to avoid going over, you need to limit the second part of the iteration to 12-(the first number).
然后,您将使用另一个范围,但是对于这个范围,为避免超出,您需要将迭代的第二部分限制为 12-(第一个数字)。 The last number will be completely dependant on the others, giving you 12-(the first number)-(the second number), its purpose only to fill the gap between the first number, the second number, and 12. In python, this would look like:
最后一个数字将完全依赖于其他数字,给您 12-(第一个数字)-(第二个数字),其目的只是填补第一个数字、第二个数字和 12 之间的空白。在 python 中,这个看起来像:
x = []
for a in range(0, 13):
for b in range(0, (13-a)):
c = 12-a-b
x.append((a, b, c))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.