python编码获取排列组合的全部情况数及Python内置函数获取排列组合

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]
                yield tuple(pool[i] for i in indices[:r])
                break
        else:
            return

或者

def permutations(iterable, r=None):
    pool = tuple(iterable)
    n = len(pool)
    r = n if r is None else r
    for indices in product(range(n), repeat=r):
        if len(set(indices)) == r:
            yield tuple(pool[i] for i in indices)
实现组合算法C(n,k),可以用递归实现:
import copy    #实现list的深复制

def combine(lst, l):
    result = []
    tmp = [0]*l
    length = len(lst)
    def next_num(li=0, ni=0):
        if ni == l:
            result.append(copy.copy(tmp))
            return
        for lj in range(li,length):
            tmp[ni] = lst[lj]
            next_num(lj+1, ni+1)
    next_num()
    return result

实现排列算法A(n,k),用递归实现:

import copy

def permutation(lst,k):
    result = []
    length = len(lst)
    tmp = [0]*k
    def next_num(a,ni=0):
        if ni == k:
            result.append(copy.copy(tmp))
            return
        for lj in a:
            tmp[ni] = lj
            b = a[:]
            b.pop(a.index(lj))
            next_num(b,ni+1)
    c = lst[:]
    next_num(c,0)
    return result
def perm(ss):  
    if len(ss)<=1:  
        return ss  
    else:  
        i=0
        for num in range(len(ss)):  
            ss[num],ss[i]=ss[i],ss[num]  
            return ss
	    i+=1
	    perm(ss[i:])  
            ss[num],ss[i]=ss[i],ss[num]  

 Python内置函数itertools 
  

C(n,k)例如C(5,2)

>>>fromitertoolsimportcombinations

>>>combins =combinations(range(5),2)

A(n,k)例如A(5,2)

>>>from itertoolsimportpermutations

>>>perms = permutations(range(5),2)

 
 

你可能感兴趣的:(python编码获取排列组合的全部情况数及Python内置函数获取排列组合)