[英]Using recursion to create a list combination
I'm in trouble creating a combination of elements from list. 我在列表中创建元素组合时遇到了麻烦。
What i would like to do is to create a recursive function in Python which returns a combination of elements for example list a = [1,2,3,4,5,6,7,8]
and a result will be combinations [1,2,3,4],[1,3,4,5],[1,4,5,6],[1,2,4,5] etc. For 8 elements it should return 70 combinations (if i did my math right). 我想要做的是在Python中创建一个递归函数,它返回一个元素组合,例如list a = [1,2,3,4,5,6,7,8]
,结果将是组合[1 ,2,3,4],[1,3,4,5],[1,4,5,6],[1,2,4,5]等。对于8个元素,它应该返回70个组合(如果我我的数学是正确的)。 Although the best option would be that the combinations don't repeat. 虽然最好的选择是组合不重复。
I tried to code it, but what i get is only [1,2,3,4],[1,3,4,5] etc
but not combination [1,5,7,8]
我试着编码它,但我得到的只是[1,2,3,4],[1,3,4,5] etc
但不是组合[1,5,7,8]
I know there is a special function but i'd like to do it recursively. 我知道有一个特殊功能,但我想以递归方式进行。 Any suggestions? 有什么建议么?
nimed = ["A","B","C","D","E","F","G","H"]
def kombinatsioonid(listike,popitav):
if len(listike) < 4:
return
tyhi = []
for c in range(len(listike)):
tyhi.append(listike[c])
listike.pop(popitav)
print(tyhi)
kombinatsioonid(listike,popitav)
kombinatsioonid(nimed,1)
This can be done in this way : 这可以通过这种方式完成:
def combination(l,n, mylist=[]):
if not n: print(mylist)
for i in range(len(l)):
mylist.append(l[i])
combination(l[i+1:], n-1, mylist)
mylist.pop()
l = ["A","B","C","D","E","F","G","H"]
n=4
combination(l, n)
For each element x
in a
, generate all k-1
combinations from the elements right to it, and prepend x
to each one. 对于每个元素x
在a
,产生所有k-1
从元件权它的组合,并且在前面加上x
到每一个。 If k==0
, simply return one empty combination, thus exiting the recursion: 如果k==0
,则只返回一个空组合,从而退出递归:
def combs(a, k):
if k == 0:
return [[]]
r = []
for i, x in enumerate(a):
for c in combs(a[i+1:], k - 1):
r.append([x] + c)
#print '\t' * k, k, 'of', a, '=', r
return r
Uncomment the "print" line to see what's going on. 取消注释“打印”行以查看正在发生的事情。
As a side note, it's better to use English variable and function names, just for the sake of interoperability (your very question being an example). 作为旁注,最好使用英文变量和函数名称,只是为了互操作性(你的问题就是一个例子)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.