[英]Number of combinations given range
Say you are given a range of numbers, [1,2,3]
where r = 3
假设给你一个数字范围
[1,2,3]
其中r = 3
and you are required to find the number of combinations of numbers that can be formed given a min and max group size.并且您需要找到在给定最小和最大组大小的情况下可以形成的数字组合的数量。 For example,
例如,
min = 1
max = 3
Can have the following configurations:可以有以下配置:
Config 1: [1, 2, 3]
Config 2: [1, 2] [3]
Config 3: [1, 3] [2]
Config 4: [2, 3] [1]
Config 5: [1] [2, 3]
Config 6: [2] [1, 3]
Config 7: [3] [1, 2]
Config 8: [1] [2] [3]
Config 9: [1] [3] [2]
Config 10: [2] [1] [3]
Config 11: [2] [3] [1]
Config 12: [3] [1] [2]
Config 13: [3] [2] [1]
The order matters: [1] [2] is different from [2] [1], but [1, 2] is the same as [2, 1]顺序很重要:[1] [2] 与 [2] [1] 不同,但 [1, 2] 与 [2, 1] 相同
More examples:更多示例:
r = 7, min = 2, max = 7
will yield 1730将产生 1730
r = 7, min = 2, max = 3
will yield 1400 as将产生 1400 作为
[1,2,3], [4,5,6] 3 3 = ncr(7,3) * ncr(4, 3) = 140
[1,2,3], [4,5], [6,7] 3 2 2 = ncr(7,3) * ncr(4, 2) * 3 = 630
[1,2], [3,4], [5,6] 2 2 2 = ncr(7,2) * ncr(5, 2) * ncr(3, 2) = 630
r = 7, min = 2, max = 2
will yield 630 as将产生 630 作为
(ncr(7,2) * ncr(5, 2) * ncr(3,2)) = 630
This gets progressively more difficult as the numbers get larger.随着数字越来越大,这变得越来越困难。 The question is, how do i write a function that takes in r, a, b that is able to give me the number of different configurations?
问题是,我如何编写一个包含 r、a、b 的 function,它能够给我不同配置的数量? I cannot wrap my head around the combinations and permutations for this.
我无法理解为此的组合和排列。
Edit: Added in more examples and made question more specific for the end goal编辑:添加了更多示例并使问题更具体地针对最终目标
I'm skeptical that, with three parameters, there's a nice closed form, but the memoized recursive function below should do the trick.我怀疑,有三个参数,有一个很好的封闭形式,但下面的记忆递归 function 应该可以解决问题。
import functools
import math
@functools.cache
def count(r, min, max):
if r < 0:
return 0
if r < min:
return 1
return sum(math.comb(r, k) * count(r - k, min, max) for k in range(min, max + 1))
if __name__ == "__main__":
def test(r, min, max):
print("X={}, Y={}, Z={} --> {}".format(r, min, max, count(r, min, max)))
test(3, 1, 3)
test(7, 2, 7)
test(7, 2, 3)
test(7, 2, 2)
Output: Output:
X=3, Y=1, Z=3 --> 13
X=7, Y=2, Z=7 --> 1730
X=7, Y=2, Z=3 --> 1400
X=7, Y=2, Z=2 --> 630
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.