不使用“itertools.combinations”的组合 [英] Combinations without using "itertools.combinations"

查看:122
本文介绍了不使用“itertools.combinations”的组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



如果一个列表包含:seq = ['A','B',' C']
的输出将是com = [['A','B'],['A','C'],['B','C']]



所有这些没有itertools.combinations方法。

我习惯于将这段代码用于排列。但是,我怎么能修改代码,使它与组合工作?

  def permute(seq):

如果len(seq)<= 1:
perms = [seq]
else:
perms = []
for i in range(len(seq)) :
sub = permute(seq [:i] + seq [i + 1:])
for sub in:
perms.append(seq [i:i + 1] + p )

return perms


解决方案

如果您不想使用 itertools ,请使用 $ b

  def组合(iterable,r):
#组合('ABCD',2) - > AB AC AD BC BD CD
#组合(范围(4),3) - > 012 013 023 123
pool = tuple(可迭代)
n = len(pool)
if r> n:
返回
指数=范围(r)
产生元组(指数为i的池[i])
,而真:
(r)):
如果指数[i]!= i + n - r:
break
else:
return
indices [i] + = 1 $
指数[j] =指数[j-1] + 1
产生元组(指数为i的池[i])


What I'd need is to create combinations for two elements a time.

if a list contains: seq = ['A', 'B', 'C'] the output would be com = [['A', 'B'], ['A', 'C'], ['B', 'C']]

all this without "itertools.combinations" method.

I was used to use this code for the permutations. But how could I modify the code to make it work with the combinations?

def permute(seq):

    if len(seq) <= 1:
        perms = [seq]
    else:
        perms = []
        for i in range(len(seq)):
            sub = permute(seq[:i]+seq[i+1:]) 
            for p in sub:    
                perms.append(seq[i:i+1]+p)

return perms

解决方案

If you don't want to use itertools, then use the documented pure-Python equivalent:

def combinations(iterable, r):
    # combinations('ABCD', 2) --> AB AC AD BC BD CD
    # combinations(range(4), 3) --> 012 013 023 123
    pool = tuple(iterable)
    n = len(pool)
    if r > n:
        return
    indices = range(r)
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != i + n - r:
                break
        else:
            return
        indices[i] += 1
        for j in range(i+1, r):
            indices[j] = indices[j-1] + 1
        yield tuple(pool[i] for i in indices)

这篇关于不使用“itertools.combinations”的组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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