码迷,mamicode.com
首页 > 编程语言 > 详细

用python实现全排列

时间:2017-04-22 12:38:43      阅读:238      评论:0      收藏:0      [点我收藏+]

标签:children   print   end   code   utf-8   .com   nbsp   str   got   

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

标签:children   print   end   code   utf-8   .com   nbsp   str   got   

原文地址:http://www.cnblogs.com/coolor/p/6747218.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!