给定字符串的所有可能组合

All possible combinations of a given string

我需要找到给定字符串的所有可能组合,从最小长度到最大长度。

interface allCombos(string: String, min: Number, max:Number): Array {}

因此,如果我的输入字符串是 ‘abcde’,并且我的最小长度是 3,我希望结果是:

对于长度 3:

[‘abc’, ‘abd’, ‘abe’, ‘acd’, ..., ‘bcd’, ‘bce’, ..., ‘eda’, ...]

与长度 4 连接:

[‘abcd’, ‘abdc’, ‘acdb’, ‘acbd’, …etc]

连接所有可能的组合,长度不超过最大参数。不应大于输入字长。

我开始认为所有可能的组合都是 ∑(3! + 4! + … + n!)。但后来我发现我错了,因为对于每个长度子集,整个世界都有很多组合(例如 6 个字母字符串的 3 种长度组合)。

社区可以帮我解决这个问题吗?

解决方案可以是 JavaScriptPython 甚至是伪代码。

编辑

为了知识的缘故。谁能回答我,在这种情况下描述结果大小的公式?我知道这不是 ∑(3! + 4! + … + n!).

您可以为此使用 itertools.combinations

from itertools import combinations

["".join(li) for li in combinations('abcde', 3)]

这会给

['abc', 'abd', 'abe', 'acd', 'ace', 'ade', 'bcd', 'bce', 'bde', 'cde']

简要说明:

list(combinations('abcde', 3))

会给

[('a', 'b', 'c'),
 ('a', 'b', 'd'),
 ('a', 'b', 'e'),
 ('a', 'c', 'd'),
 ('a', 'c', 'e'),
 ('a', 'd', 'e'),
 ('b', 'c', 'd'),
 ('b', 'c', 'e'),
 ('b', 'd', 'e'),
 ('c', 'd', 'e')]

所以你的三个字母的所有组合。您可以在列表理解中加入各个元组。

如果你愿意,你当然可以很容易地把它放在一个循环中:

min_length = 3
max_length = 5

res = {str(i): ["".join(li) for li in combinations('abcde', i)] for i in range(min_length, max_length + 1)}

这给出了

{'3': ['abc', 'abd', 'abe', 'acd', 'ace', 'ade', 'bcd', 'bce', 'bde', 'cde'],
 '4': ['abcd', 'abce', 'abde', 'acde', 'bcde'],
 '5': ['abcde']}

如果您想将它放在一个列表中:

import numpy as np
final_list = np.concatenate(res.values())

产生

array(['abc', 'abd', 'abe', 'acd', 'ace', 'ade', 'bcd', 'bce', 'bde',
       'cde', 'abcde', 'abcd', 'abce', 'abde', 'acde', 'bcde'],
      dtype='|S5')

很高兴向您介绍精彩的python标准库itertools!您将需要使用组合功能。这个库的厉害之处在于它解决了几乎所有的组合循环问题。

 import itertools

 min_length = 2
 max_length = 5

 s = 'ABCDEF'
 for i in range(min_length, max_length):
     print('length', i, 'cominations')
     print([_ for _ in itertools.combinations(s, i)])

其他人向您展示了 combinations/permutations 的一些不错的选项,但我认为您的完整预期输出是这样的:

from itertools import combinations

def allCombos(str, min_length, max_length):
    str_combinations = []
    for length in range(min_length, max_length):
        combinations = [''.join(c) for c in combinations(str, length)]
        str_combinations.append(combinations)
    return str_combinations

[Edit]: For knowledge's sake. Could anyone answer me, the formula that describes the result size in this case? I know its not ∑(3! + 4! + … + n!).

在下面找到使用 JavaScript 提供相同最终结果的三种数学方法。有关该过程的更多说明,请参阅

  • Permutation
  • How to improve efficiency of algorithm which generates next lexicographic permutation?

主题中其他感兴趣的项目

const n = 4;

{
  console.log("multiplication in loop:\n");
  let l = 1,
    k;

  for (let i = k = n; l < i; k *= l++);

  console.log({
    [`${n}!`]: k
  });
}

{
  console.log("single multiplication 4 * 3 * 2 * 1:\n");
  console.log({
    [`${n}!`]: 4 * 3 * 2 * 1
  });

}

{
  console.log("multiplication in steps:\n");
  
  let curr = n;
  
  let acc = {};
  
  acc[`${curr} * ${curr - 1}`] = curr * --curr;
  
  console.log(acc);
  
  acc[`${Object.keys(acc).pop()} * ${--curr}`] = curr * +acc[Object.keys(acc).pop()];
  
  console.log(acc);
  
  acc[`${Object.keys(acc).pop()} * ${--curr}`] = curr * +acc[Object.keys(acc).pop()];
  
  console.log(acc);

}