【问题标题】:Alternate way to find all lexicographic orderings of a string in Python在 Python 中查找字符串的所有字典顺序的替代方法
【发布时间】:2021-01-05 18:50:30
【问题描述】:

问题:找出排列字符串的所有不同方式 例如。 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 循环。我应该使用什么方法来解决这个问题

【问题讨论】:

  • 什么是确切的问题表述?预期的结果是什么?
  • @MBo 我已将问题编辑到帖子中
  • itertools.combinations,它在标准库中。
  • 这不是字典的意思。 (省略了公主新娘模因。)

标签: python algorithm data-structures permutation lexicographic


【解决方案1】:

你想找到字符串的所有排列。 Python 的标准库包括一个function for this

>>> from itertools import permutations
>>> list(permutations('123'))
[('1', '2', '3'), ('1', '3', '2'), ('2', '1', '3'), ('2', '3', '1'), ('3', '1', '2'), ('3', '2', '1')]

【讨论】:

    【解决方案2】:

    其实有一个非常简单的解决方案,只需要使用itertools库;

    from itertools import permutations
    answer = [''.join(perm) for perm in permutations(s)]
    

    这为您提供了 s 的所有不同排列的列表, 例如

    s = 'abc'
    

    那么答案是:

    answer = ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
    

    【讨论】:

      猜你喜欢
      • 2018-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-11
      • 1970-01-01
      • 2014-11-07
      • 2023-04-07
      • 1970-01-01
      相关资源
      最近更新 更多