Python实现排列组合算法

实现组合算法C(n,k),可以用递归实现:

python代码:

 1 import copy    #实现list的深复制
 2 
 3 def combine(lst, l):
 4     result = []
 5     tmp = [0]*l
 6     length = len(lst)
 7     def next_num(li=0, ni=0):
 8         if ni == l:
 9             result.append(copy.copy(tmp))
10             return
11         for lj in range(li,length):
12             tmp[ni] = lst[lj]
13             next_num(lj+1, ni+1)
14     next_num()
15     return result

 

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

k=len(lst)s时,为全排列

 1 import copy
 2 
 3 def permutation(lst,k):
 4     result = []
 5     length = len(lst)
 6     tmp = [0]*k
 7     def next_num(a,ni=0):
 8         if ni == k:
 9             result.append(copy.copy(tmp))
10             return
11         for lj in a:
12             tmp[ni] = lj
13             b = a[:]
14             b.pop(a.index(lj))
15             next_num(b,ni+1)
16     c = lst[:]
17     next_num(c,0)
18     return result
posted @ 2016-05-08 22:14  Mr_DaLiN  阅读(8929)  评论(0编辑  收藏  举报