获取字符串的所有组合 [英] Get every combination of strings

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

问题描述

我有一个组合作业,涉及从特定的字符串组合中获取长度小于或等于6的每个单词。

I had a combinatorics assignment that involved getting every word with length less than or equal to 6 from a specific combination of strings.

在这种情况下,它是S = {'a','ab','ba'}。教授刚刚开始列出它们,但是我认为使用程序可以更轻松地解决它们。唯一的问题是,我无法获得一种可以实际计算所有可能选项的好的算法。

In this case, it was S = { 'a', 'ab', 'ba' }. The professor just started listing them off, but I thought it would be easier solved with a program. The only problem is that I can't get a good algorithm that would actually compute every possible option.

如果有人可以提供帮助,我将不胜感激。我通常使用Python进行编程,但实际上我只需要算法的帮助。

If anyone could help, I'd appreciate it. I usually program in Python but really I just need help with the algorithm.

推荐答案

您可以迭代地生成由一个字符串构成的所有字符串部分,两部分,三部分,依此类推,直到一个步骤中生成的所有字符串都超过六个字符为止。进一步的步骤将只生成更长的字符串,因此所有可能的短字符串都已经生成。如果在每个步骤中收集这些短字符串,最终都会得到一组所有可能生成的短字符串。

You can iteratively generate all the strings made from one part, two parts, three parts and so on, until all the strings generated in a step are longer than six characters. Further steps would only generate even longer strings, so all possible short strings have already been generated. If you collect these short strings in each step you end up with a set of all possible generated short strings.

在Python中:

S = set(['a', 'ab', 'ba'])

collect = set()
step = set([''])
while step:
   step = set(a+b for a in step for b in S if len(a+b) <= 6)
   collect |= step

print sorted(collect)

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

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