nCk函数从python中的n个元素列表中选择了k个元素
我正在尝试编写一个函数,用python从列表中生成nCk 例如,从配对列表中:nCk函数从python中的n个元素列表中选择了k个元素,python,recursion,combinatorics,Python,Recursion,Combinatorics,我正在尝试编写一个函数,用python从列表中生成nCk 例如,从配对列表中: ['a', 'b', 'c'] 输出应为: [['a','b'],['a','c'],['b','c']] 但是我没有得到任何输出 以下是我的尝试: def chose(elements, k): output = [] for i in range(len(elements)): if k == 1: output.append(elements[i])
['a', 'b', 'c']
输出应为:
[['a','b'],['a','c'],['b','c']]
但是我没有得到任何输出
以下是我的尝试:
def chose(elements, k):
output = []
for i in range(len(elements)):
if k == 1:
output.append(elements[i])
for c in chose(elements[i+1:], k-1):
output.append(elements[i])
output.append(c)
return output
print chose(['a', 'b', 'c'],2)
如果要查找所有组合,请使用
itertools.compositions
,您是否可以告诉我函数有什么问题
from itertools import combinations
a = ['a', 'b', 'c']
result = [list(i) for i in combinations(a,2)]
有关combinations()
函数的文档和实现,请访问
更新
此函数应执行您想要的操作:
def chose(elements, k):
output = []
if k == 1:
return [[i] for i in elements]
else:
for i in range(len(elements)):
head = elements[i]
tails = chose(elements[i+1:], k-1)
output += [[head] + tail for tail in tails]
return output
print chose(['a','b','c'], 2)
您可以在不使用任何导入的情况下使用电源集:
def power_set(items,k):
n = len(items)
for i in xrange(2**n):
combo = []
for j in xrange(n):
if (i >> j) % 2 == 1:
combo.append(items[j])
if len(combo) == k:
yield combo
print(list(power_set(['a', 'b', 'c'],2)))
[['a', 'b'], ['a', 'c'], ['b', 'c']]
不幸的是,我们不允许使用libs:|在我发布的链接上查找
iterfunction.composition()
的实现。如果不允许使用libs,您可以复制它。。建议阅读。另外,请查看: