一个单词的所有可能组合-Python [英] All possible combinations of a word - Python

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

问题描述

我正在编写一个程序,在其中插入一些字母,然后输出是该字母的所有可能组合。

I am making a program where you insert some letters and then the output are all the posible combinations of that letters.

例如:如果输入为 ABC 输出应为 A, B, C, AB, AC, BC, ABC, ACB等...

For example: if the input is "ABC" the output should be "A","B","C","AB","AC","BC","ABC","ACB" and so on...

最后,我的想法是将所有组合放在一个集合中,以便可以与包含特定英语单词词典的另一个集合相交,即理想输出的交集

Finally, my idea is to put all that combinations in a set so that it can be intersect with another set containing a certain dictionary of english words being that intersection the ideal output

到目前为止,我的脚本是这样的:

As far, my script is this one:

import random

p = list(raw_input('Insert some letters: '))

p2 = []

p3 = []
for j in range((len(p))):
    p2.append(p[j])

for i in range(len(p)):
    a = random.sample(p2,len(p))
    p3.append(str("".join(a)))
    print p3[]

很显然,这里有一些错误,并且不完整。您可以帮助我完成或告诉我应该走哪条路吗?感谢您的阅读

Obviously, there are some errors and its not complete. Can you help me to finish or tell me which path should I take? Thanks for reading

推荐答案

如果您不关心订单,便在寻找一种组合。您可以为此使用 itertools.combination

If you don't care about order, you are looking for a combination. You can use itertools.combination for this:

import itertools

items = 'ABC'
for i in range(len(items)+1):
    for combination in itertools.combinations('ABC', i): 
        print(combination)

列表理解版本:

[combination for i in range(len(items)+1) for combination in itertools.combinations('ABC', i)]

这篇关于一个单词的所有可能组合-Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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