如何在Python中找到给定字符串的所有可能排列?
要查找给定字符串的所有可能排列,可以使用itertools模块,该模块具有一个称为permutations(iterable[,r])的有用方法。此方法以元组形式返回可迭代元素的连续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
热门推荐
2 十月简短祝福语
7 初八祝福语简短语
10 周一情人祝福语简短
11 给孙子拜年祝福语简短
12 祖国七十华诞简短祝福语
13 对离岗同事祝福语简短
14 早晨好正能量祝福语简短
15 八十大寿简短祝福语
16 生日果酒祝福语简短独特
17 公司开年仪式祝福语简短
18 给长辈祝福语简短大全