Python|查找字符串的所有排列的方法
给定一个字符串,编写一个Python程序来找出一个字符串的所有可能排列。让我们讨论一些解决问题的方法。
方法#1:使用朴素方法
Python3
# Python code to demonstrate
# to find all permutation of
# a given string
# Initialising string
ini_str = "abc"
# Printing initial string
print("Initial string", ini_str)
# Finding all permutation
result = []
def permute(data, i, length):
if i == length:
result.append(''.join(data) )
else:
for j in range(i, length):
# swap
data[i], data[j] = data[j], data[i]
permute(data, i + 1, length)
data[i], data[j] = data[j], data[i]
permute(list(ini_str), 0, len(ini_str))
# Printing result
print("Resultant permutations", str(result))
Python3
# Python code to demonstrate
# to find all permutation of
# a given string
from itertools import permutations
# Initialising string
ini_str = "abc"
# Printing initial string
print("Initial string", ini_str)
# Finding all permutation
permutation = [''.join(p) for p in permutations(ini_str)]
# Printing result
print("Resultant List", str(permutation))
输出:
Initial string abc
Resultant permutations ['abc', 'acb', 'bac', 'bca', 'cba', 'cab']
方法 #2:使用 itertools
Python3
# Python code to demonstrate
# to find all permutation of
# a given string
from itertools import permutations
# Initialising string
ini_str = "abc"
# Printing initial string
print("Initial string", ini_str)
# Finding all permutation
permutation = [''.join(p) for p in permutations(ini_str)]
# Printing result
print("Resultant List", str(permutation))
输出:
Initial string abc
Resultant List ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']