首页 > 代码库 > python一中实现组合的方式

python一中实现组合的方式

方式1:
#!/usr/bin/env python
#-*- encoding: utf-8 -*-

def permutations(iterable, r=None):
    # permutations(‘ABCD‘, 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
    # permutations(range(3)) --> 012 021 102 120 201 210
    pool = tuple(iterable)
    n = len(pool)
    r = n if r is None else r
    if r > n:
        return
    indices = range(n)
    cycles = range(n, n-r, -1)
    yield tuple(pool[i] for i in indices[:r])
    while n:
        for i in reversed(range(r)):
            cycles[i] -= 1
            if cycles[i] == 0:
                indices[i:] = indices[i+1:] + indices[i:i+1]
                cycles[i] = n - i
            else:
                j = cycles[i]
                indices[i], indices[-j] = indices[-j], indices[i]
                print indices
                yield tuple(pool[i] for i in indices[:r])
                break
        else:
            return

for x in  permutations(xrange(1,6),3):
    print x

 

方式2:

#/usr/bin/env python
# -*-encoding:utf-8 -*-
http://blog.csdn.net/wklken/article/details/8453107
from time import time
#生成全排列
def perm(items, n=None):
    lg=len(items)
    r=n if n is not None else lg
    for i in xrange(lg):
        v = items[i:i + 1]
        if r == 1:
            yield v
        else:
            rest = items[:i] + items[i + 1:]
            for p in perm(rest, r - 1):
                yield v + p
#生成组合         
def comb(items, n=None):
    if n is None:
        n = len(items)    
    for i in xrange(len(items)):
        v = items[i:i + 1]
        if n == 1:
            yield v
        else:
            rest = items[i + 1:]
            for c in comb(rest, n - 1):
                yield v + c
                
if __name__==‘__main__‘:
    t=time()
    for i in perm(range(1,20),3):
        print i
    print ‘use time:‘,time()-t

 

#!/usr/bin/env python
# -*- encoding:utf-8 -*-

from time import time
def permutations(lst,n=None):
    num=len(lst)
    if num<n:
        print ‘n is more than the length of list‘
        return
    else:
        r= num if n is None else n       
    tmp=range(num)#用tmp值的下标对应mytup的值   
    cyc=range(num,num-r,-1)#用于循环,保证选出次数 
    yield [lst[i] for i in tmp[:r]]    
    while 1:
        for i in reversed(range(r)):
            cyc[i]-=1
            if cyc[i]==0:
                tmp[i:]=tmp[i+1:]+tmp[i:i+1]
                cyc[i] =num - i
            else:
                j=cyc[i]
                tmp[i],tmp[-j]=tmp[-j],tmp[i]
                yield [lst[i] for i in tmp[:r]]
                break
        else:
            return
if __name__==‘__main__‘:
    t=time()        
    for x in permutations(xrange(1,20),3):
        print x
    print "total run time:",time()-t

python一中实现组合的方式