微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 Python 中查找字符串的所有字典顺序的另一种方法

如何解决在 Python 中查找字符串的所有字典顺序的另一种方法

问题:找出排列字符串的所有不同方式 例如。 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']

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。