【问题标题】:how to calculate Permutations from a range of 3 to 7 characters如何计算 3 到 7 个字符范围内的排列
【发布时间】:2020-07-21 17:32:58
【问题描述】:

我在这里搜索过: Python 3 How to find the different combinations of a String 并找到了这个功能:

import itertools
string = 'Peaches Apples Bananas'
word_list = string.split(' ')
output = [' '.join(permutation) for permutation in itertools.permutations(word_list)]

其实我有这个字符串的例子 'N A E C H S W' 并且正在选择从 3 到字符串长度的字符 我已经这样做了,一个 for 3 在 (3, length) 的范围内,另一个 for ....

j =0 
while j < 4:
    for i in range (3+j,lng+1):
        scpy = word_list[j:i]
        scpy_tx =""
            for k  in scpy:
            scpy_tx = scpy_tx + str(k)
        print(i, j, scpy, scpy_tx)
    j= j +1

给出这个输出:

3 0 ['N', 'A', 'E'] NAE
4 0 ['N', 'A', 'E', 'C'] NAEC
5 0 ['N', 'A', 'E', 'C', 'H'] NAECH
6 0 ['N', 'A', 'E', 'C', 'H', 'S'] NAECHS
4 1 ['A', 'E', 'C'] AEC
5 1 ['A', 'E', 'C', 'H'] AECH
6 1 ['A', 'E', 'C', 'H', 'S'] AECHS
5 2 ['E', 'C', 'H'] ECH
6 2 ['E', 'C', 'H', 'S'] ECHS
6 3 ['C', 'H', 'S'] CHS

我提供给 a.m. 置换公式的这个输入:

output = [' '.join(permutation) for permutation in itertools.permutations(scpy)] 

然而,我的方法缺少许多组合,即尚未考虑所有 nedded 字符:

'N A E S'  'N A E S W'  'N A C H W'
'N E C H'  'N A S'  'N H W'

和其他的没有像放在üermutation公式中一样。

如何计算所有给定字符的长度从 3 到 7 的所有可能排列?

目前我没有好主意;并且我的数学较新。

【问题讨论】:

  • [''.join(perm) for r in range(3, 8) for perm in itertools.permutations('NAECHSW', r)] 有什么问题
  • 对不起;我是这种材料的新手,不知道第二个论点

标签: python-3.x string combinations permutation


【解决方案1】:

permutations 有第二个长度参数,您可以针对所需的每个长度对其进行迭代,然后将它们与itertools.chain 一起收集:

from itertools import permutations, chain

chars = 'NAECHSW'
all_perms = chain.from_iterable(
    permutations(chars, perm_len) 
    for perm_len in range(3, len(chars)+1)
)
for p in all_perms:
    print(''.join(p))

使用chain 使all_perms 完全惰性化,因此它不会占用任何额外的内存。

【讨论】:

  • 谢谢。同时我使用了 collections.Counter: 并找到了一个函数 isSublist(sub, main)。 A 将在适当的时候再次查看排列方法:首先让我对您的帮助表示感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-28
相关资源
最近更新 更多