一个全排列算法

#!/usr/bin/env python

"""递归全排列算法"""

import copy 

def permutate(aList):
	"""生成输入序列的全排列

	输入列表,以列表的形式返回列表中元素的所有可能排列序列"""

	result = []
	# 如果输入序列为空或仅有一个元素
	# 它的全排列就是它本身
	if len(aList) <= 1:
        	result.append(aList)
        	return result
    
	# 否则
	# perm( x1 ,x2,...xn) = {  {perm(x1 ,...xn-1)xn}, 
	#                          {perm(x1, ...xn-2, xn)xn-1}
	#                           ......
	#                          {perm(x2, ... xn)x1} } }}
    for item in reversed(aList):
        tmpList = copy.copy(aList) # 浅拷贝
        tmpList.remove(item)
        for perm in permutate(tmpList):
            perm.append(item)
            result.append(perm)
	return result                                                      


# 测试
def __fact(n):
	"""求阶乘"""
	if n == 0:
		return 1
	return n * __fact(n - 1)

def __test():
	for i in range(10):
		testList = range(i)
        result = permutate(testList)
        if i == 0 and result == []:
        	continue
        assert len(result) == fact(i)

if __name__ == '__main__':
	__test()  
 
 

 

 

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