python編碼獲取排列組合的全部情況數及Python內建函式獲取排列組合
阿新 • • 發佈:2019-02-20
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)