Python编程练习.全排列和全组合

利用Python实现经典算法:全排列和全组合


1.全排列

根据python文档中的itertools.permutations方法进行排列

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 = list(range(n))
    cycles = list(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

2.全组合

(1)根据python文档中的itertools.combinations方法进行排列

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 = list(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)

(2)根据位运算进行组合

def combinations(str):
    n=2**len(str)
    for i in range(n):
        bits=[i>>offset&1 for offset in range(len(str)-1,-1,-1)]
        current=[str[index] for (index,bit) in enumerate(bits) if bit==1]
        print(''.join(current));
  • 参考:
    【Python: 实现全组合】(https://www.polarxiong.com/archives/Python-实现全组合.html)
    【itertools函数】(https://docs.python.org/3/library/itertools.html?highlight=itertools)

你可能感兴趣的:(python)