首页 > 代码库 > 用python实现全排列

用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实现全排列