Using recursion to create a list combination

大憨熊 提交于 2021-02-10 19:49:12

问题


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). 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]

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) 

回答1:


For each element x in a, generate all k-1 combinations from the elements right to it, and prepend x to each one. If k==0, simply return one empty combination, thus exiting the recursion:

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).




回答2:


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)


来源:https://stackoverflow.com/questions/26136673/using-recursion-to-create-a-list-combination

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!