[英]Get n in exact k parts. Recursion and partition algorithm. p(n,k)
I'm looking to enumerate all the partitions of n in k parts. 我想枚举k个部分中n的所有分区。
So for p(5,3) i'd get 2 partitions of k = 3 => (3,1,1), (2,2,1). 因此对于p(5,3)我将得到k = 3 =>(3,1,1),(2,2,1)的2个分区。
Here's what I found from searching and looking through stackoverflow : 这是我通过搜索和查找stackoverflow发现的:
def p(n,k):
lst = []
if n < k:
return lst
elif k == 1:
return lst
elif k == n:
return lst
else:
p(n-1, k-1)
p(n-k, k)
return lst
^^^^ This is the form i want, ^^^^这是我想要的形式,
As it is, finding the sum of k parts is easy, you return p(n-1, k-1) + p(nk,k). 实际上,找到k个部分的和很容易,您将返回p(n-1,k-1)+ p(nk,k)。 As for me, I need to list each element like so [(3,1,1), (2,2,1)].
对于我来说,我需要像[[3,1,1),(2,2,1)]这样列出每个元素。
My main problem is to "build" those partitions recursively. 我的主要问题是递归“构建”那些分区。 How would you tackle this?
您将如何解决?
Edit 编辑
If you get base case k = 1, add + 1, k-1 times. 如果得到基本情况k = 1,则加+ 1,k-1次。 (4,1) then (4,1,1)
(4,1)然后(4,1,1)
If you get base case k = n, split up and remove one to each part. 如果得到基本情况k = n,则拆分并为每个部分删除一个。
Like so : (3,3) then (3,3,3) then (2,2,2) 像这样:(3,3)然后(3,3,3)然后(2,2,2)
If you get base case k < n, nothing 如果得到基本情况k <n,则无
Basically, my problem is to "stack" up the ones from base case to top and get a complete list p(6,3) = [(2,2,2), (4,1,1), (3,2,1)] 基本上,我的问题是从基本情况到顶部“堆叠”并获得完整列表p(6,3)= [(2,2,2),(4,1,1),(3,2 ,1)]
I would add to the recursive function a third parameter m
which is the maximum value an element can have in the partition. 我将在递归函数中添加第三个参数
m
,这是元素在分区中可以具有的最大值。 Then I would define the function like this: 然后,我将这样定义函数:
def p(n, k, m=None):
if m is None:
m = n - k + 1 # maximum can be n - k + 1 since minimum is 1
if k == 0:
if n == 0:
yield ()
return
for i in xrange(1, m + 1): # first could be from 1 to the maximum
# the rest of the sum will be n - i among k - 1 elements with
# maximum i
for t in p(n - i, k - 1, i):
yield (i, ) + t
Examples: 例子:
>>> list(p(10, 3))
[(4, 3, 3), (4, 4, 2), (5, 3, 2), (5, 4, 1), (6, 2, 2), (6, 3, 1), (7, 2, 1), (8 , 1, 1)]
>>> list(p(6, 2))
[(3, 3), (4, 2), (5, 1)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.