如何用 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