给定字符串的所有可能组合 [英] All possible combinations of a given string

查看:145
本文介绍了给定字符串的所有可能组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to find all possible combinations of a given string, from a minimum length to a maximum length.

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

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

So if my input string is ‘abcde’, and my minimum length is 3, I want the result to be:

长度3:

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

与长度4连接:

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

由所有可能的组合(长度最大为max)连接。

Concatenated with all possible combinations with length up to the max parameter. Which shouldn't be higher than the input word length.

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

I started thinking that all possible combinations would be ∑(3! + 4! + … + n!). But then I saw I'm wrong because for every length subset, there are many combinations for the whole world (for example 3-length combinations of a 6 letter string).

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

Can the community help me with this problem?

解决方案可以在 JavaScript Python 甚至是伪代码。

The solution can either be in JavaScript, Python or even pseudo code.

编辑

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

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!).

推荐答案

您可以使用 itertools .combinations

You can use itertools.combinations for this:

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')]

所有组合thr您的信件的ee。您可以加入单个元组,然后进行列表理解。

so all combinations of three of your letters. You can join the individual tuples then in a list comprehension.

如果愿意,您当然可以轻松地将其放入循环中。

You can then of course easily put this in a loop if you like:

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']}

如果您希望将其包含在一个列表中:

If you want to have it in a single list:

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')

这篇关于给定字符串的所有可能组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆