问题描述
问题:找出排列字符串的所有不同方式 例如。 123可排列--123,132,213,231,321,312
所以老实说我不知道如何设计这个问题的解决方案,因为我没有上过任何官方的数据结构和算法课程,但我想出了一个更数学的解决方案,我能够把它变成代码:
if __name__ == '__main__':
string = 'ABCD'
count = 0
for first in string:
if first is not string[0]:
print()
for second in string:
if second is first:
continue
for third in string:
if third in [second,first]:
continue
for fourth in string:
if fourth in [third,second,first]:
continue
count += 1
print(str(first)+str(second)+str(third)+str(fourth),end=',')
print('\n{} possible combinations'.format(count))
但我必须根据字符串的大小手动添加或删除 for 循环。我应该使用什么方法来解决这个问题
解决方法
您想找到字符串的所有排列。 Python 的标准库包含一个 function for this。
>>> from itertools import permutations
>>> list(permutations('123'))
[('1','2','3'),('1','3','2'),('2','1','1'),('3','1')]
,
其实有一个非常简单的解决方案,只需使用itertools 库;
from itertools import permutations
answer = [''.join(perm) for perm in permutations(s)]
这为您提供了 s 的所有不同排列的列表, 例如
s = 'abc'
那么答案是:
answer = ['abc','acb','bac','bca','cab','cba']