首页 > 代码库 > 用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实现全排列
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。