输出给定集合的所有排列与组合-python

输出全部排列:

算法思想如下:假设集合中有元素1...n,对于每一个元素k,使之为排列第一元素,然后递归求其余n-1个元素的全排列。将结果合并,输出即可,可保证无重复,并且结果是升序。代码如下:

'''
Created on 2013-4-9

@author: shatangju
'''
def perm(items, n=None):
    if n == None:
        n = len(items)
    for i in xrange(len(items)):
        v = items[i: i+1]
        if len(items) == 1:
            yield v
        else:
            rest = items[:i] + items[i+1:]
            for p in perm(rest, n-1):
                yield v + p
        
        
items = [1, 2, 3, 4, 5]
for a in perm(items):
    print a



输出全部组合:

算法思想如下:假设集合中有元素1...n,  对于每一个元素k,其皆有可能在组合中或不在组合中。所以求出其余n-1个元素的组合后,输出两个结果:含k与不含k。结果保证无重复。代码如下:

'''
Created on 2013-4-16

@author: shatangju
'''
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
            yield []
        else:
            rest = items[i+1:]
            for c in comb(rest, n-1):
                yield v+c
                yield c

items = [1, 2, 3, 4, 5]
num = 0
for combination in comb(items):
    print combination   
    num+=1
print num   



你可能感兴趣的:(算法,python)