使用递归创建列表组合 [英] Using recursion to create a list combination

查看:51
本文介绍了使用递归创建列表组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法从列表中创建元素组合.

I'm in trouble creating a combination of elements from list.

我想做的是在 Python 中创建一个递归函数,它返回元素的组合,例如列表 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 个组合(如果我的数学计算正确的话).虽然最好的选择是组合不重复.

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.

我试图编码,但我得到的只是 [1,2,3,4],[1,3,4,5] 等 而不是组合 [1,5,7,8]

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) 

推荐答案

对于a中的每个元素x,生成所有k-1从元素到它的组合,并在每个元素前加上 x.如果k==0,只返回一个空组合,从而退出递归:

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

这篇关于使用递归创建列表组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆