【发布时间】:2018-12-03 20:47:46
【问题描述】:
我有这个组合数学问题: 令 m=(m1,...,mk) 为 k 个正整数的向量。如果对于所有 1≤i≤k,ai≤mi,则 n 的 k-组合 (a1,...,ak) 是 m 约束的。例如,(1,1,3) 和 (2,1,2) 是 5 的唯一 (2,1,4) 约束 3 分区。
编写一个函数 constrained_compositions,它接受一个自然数 n 和一个由 k 个正整数组成的向量 m,并打印 n 的所有 m-约束 k-compositions 的集合。请注意,可以从 m 推断出 k。
谷歌搜索发现了这个有用的功能:
def compositions(k, n):
# inputs: k and n are of type 'int'
# output: a set of tuples
assert n > k > 1
to_process = [[i] for i in range(1, n+1)]
while to_process:
l = to_process.pop()
s = sum(l)
le = len(l)
for i in range(1, n-s+1):
news = s + i
if news <= n:
newl = list(l)
newl.append(i)
if le == k-1 and news == n:
yield tuple(newl)
elif le < k-1 and news < n:
to_process.append(newl)
并实现以获取匹配约束的元组,如下所示:
def constrained_compositions(n, m):
# inputs: n is of type 'int' and m is a list of integers
# output: a set of tuples
k = len(m)
max_num = max(m)
l = []
comp = list(compositions(k,n))
for i in comp:
for j in i:
if j <= max_num:
l.append(i)
print(set(l))
但这是我的结果:
{(2, 3, 2), (2, 1, 4), (4, 2, 1), (5, 1, 1), (3, 3, 1), (3, 2, 2), (3, 1, 3), (1, 5, 1), (1, 4, 2), (2, 2, 3), (2, 4, 1), (1, 2, 4), (4, 1, 2), (1, 1, 5), (1, 3, 3)}
它应该是:
{(1, 1, 5), (1, 2, 4), (2, 1, 4), (2, 2, 3), (3, 1, 3), (3, 2, 2)}
提前感谢您的帮助?
【问题讨论】:
-
您是否尝试将
l设为一个集合,而不是一个列表? -
不行,让我试试!
标签: python tuples combinatorics