如何用 Python 找到给定字符串的所有可能排列?
若要找到给定字符串的所有可能排列,可以使用 itertools 模块,该模块具有一个简单易用的方法 permutations(iterable[, r])。此方法以元组形式返回 iterable 中的元素的 r 长度的连续排列。
若要将所有排列获取为字符串,需要迭代函数调用并连接元组。例如
>>>from itertools import permutations
>>>print [''.join(p) for p in permutations('dune')]
['dune','duen', 'dnue', 'dneu', 'deun', 'denu', 'udne', 'uden', 'unde', 'uned', 'uedn','uend', 'ndue', 'ndeu', 'nude',
'nued', 'nedu', 'neud', 'edun', 'ednu','eudn', 'eund', 'endu', 'enud']如果您不想使用内置方法,而是创建自己的方法,可以使用以下递归解决方案
def permutations(string, step = 0):
if step == len(string):
# we've gotten to the end, print the permutation
print "".join(string)
for i in range(step, len(string)):
# copy the string (store as array)
string_copy = [c for c in string]
# swap the current index with the step
string_copy[step], string_copy[i] =string_copy[i], string_copy[step]
# recurse on the portion of the stringthat has not been swapped yet
permutations(string_copy, step + 1)
print (permutations ('one'))输出
one oen noe neo eno eon None
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP