用python实现全排列

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用python实现全排列相关的知识,希望对你有一定的参考价值。

#coding:utf-8
def permutation(inStr, pos,  parentData):
        if len(inStr) == 0:
            return
        if len(inStr) == 1:
            print "{" + inStr + "}"
            return
        # here we need a new buffer to avoid to pollute the other nodes.
        buffer = []
        buffer.extend(parentData)
        # choose the element
        buffer.append(inStr[pos])

        # get the remnant elements.
        subStr = kickChar(inStr, pos)

        # got one of the result
        if len(subStr) == 1:
            buffer.extend(subStr)
            print buffer
            return

        # here we use loop to choose other children.
        for i in range(len(subStr)):
            permutation(subStr, i, buffer)

    # a simple method to delete the element we choose
def kickChar(src,  pos):
        srcBuf = []
        srcBuf.extend(src)
        srcBuf.pop(pos)
        return srcBuf
def main():
    input = [A,B,C,D]
    for i in range(len(input)):
        permutation(input, i, [])
main()

 

输出:

C:\Python27\python.exe D:/work/search/3.py
[‘A‘, ‘B‘, ‘C‘, ‘D‘]
[‘A‘, ‘B‘, ‘D‘, ‘C‘]
[‘A‘, ‘C‘, ‘B‘, ‘D‘]
[‘A‘, ‘C‘, ‘D‘, ‘B‘]
[‘A‘, ‘D‘, ‘B‘, ‘C‘]
[‘A‘, ‘D‘, ‘C‘, ‘B‘]
[‘B‘, ‘A‘, ‘C‘, ‘D‘]
[‘B‘, ‘A‘, ‘D‘, ‘C‘]
[‘B‘, ‘C‘, ‘A‘, ‘D‘]
[‘B‘, ‘C‘, ‘D‘, ‘A‘]
[‘B‘, ‘D‘, ‘A‘, ‘C‘]
[‘B‘, ‘D‘, ‘C‘, ‘A‘]
[‘C‘, ‘A‘, ‘B‘, ‘D‘]
[‘C‘, ‘A‘, ‘D‘, ‘B‘]
[‘C‘, ‘B‘, ‘A‘, ‘D‘]
[‘C‘, ‘B‘, ‘D‘, ‘A‘]
[‘C‘, ‘D‘, ‘A‘, ‘B‘]
[‘C‘, ‘D‘, ‘B‘, ‘A‘]
[‘D‘, ‘A‘, ‘B‘, ‘C‘]
[‘D‘, ‘A‘, ‘C‘, ‘B‘]
[‘D‘, ‘B‘, ‘A‘, ‘C‘]
[‘D‘, ‘B‘, ‘C‘, ‘A‘]
[‘D‘, ‘C‘, ‘A‘, ‘B‘]
[‘D‘, ‘C‘, ‘B‘, ‘A‘]

Process finished with exit code 0

 

代码借鉴于http://airu.iteye.com/blog/1930391的java代码

以上是关于用python实现全排列的主要内容,如果未能解决你的问题,请参考以下文章

算法之使用递归求解全排列

递归实现全排列

非递归全排列 python实现

python实现基础的深度优先搜索(DFS, depth first search)解决数的全排列问题

Java实现全排列

全排列permute,python回溯实现全排列,permute backtracking