【发布时间】: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