生成所有可能的三个字母字符串的最佳方法是什么?

时间:2011-08-16 05:46:05

标签: python performance

我正在生成所有可能的三个字母关键字e.g. aaa, aab, aac.... zzy, zzz以下是我的代码:

alphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

keywords = []
for alpha1 in alphabets:
    for alpha2 in alphabets:
        for alpha3 in alphabets:
            keywords.append(alpha1+alpha2+alpha3)

能否以更流畅有效的方式实现此功能?

7 个答案:

答案 0 :(得分:79)

keywords = itertools.product(alphabets, repeat = 3)

请参阅documentation for itertools.product。如果您需要字符串列表,请使用

keywords = [''.join(i) for i in itertools.product(alphabets, repeat = 3)]

alphabets也不需要是一个列表,它可以只是一个字符串,例如:

from itertools import product
from string import ascii_lowercase
keywords = [''.join(i) for i in product(ascii_lowercase, repeat = 3)]
如果您只想要lowercase ascii letters

将会有效。

答案 1 :(得分:15)

您也可以使用地图而不是列表理解(这是地图仍然比LC更快的情况之一)

>>> from itertools import product
>>> from string import ascii_lowercase
>>> keywords = map(''.join, product(ascii_lowercase, repeat=3))

列表理解的这种变化也比使用''.join

更快
>>> keywords = [a+b+c for a,b,c in product(ascii_lowercase, repeat=3)]

答案 2 :(得分:4)

from itertools import combinations_with_replacement

alphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

for (a,b,c) in combinations_with_replacement(alphabets, 3):
    print a+b+c

答案 3 :(得分:4)

您也可以通过简单的计算在没有任何外部模块的情况下完成此操作 PermutationIterator就是您要搜索的内容。

def permutation_atindex(_int, _set, length):
    """
    Return the permutation at index '_int' for itemgetter '_set'
    with length 'length'.
    """
    items = []
    strLength = len(_set)
    index = _int % strLength
    items.append(_set[index])

    for n in xrange(1,length, 1):
        _int //= strLength
        index = _int % strLength
        items.append(_set[index])

    return items

class PermutationIterator:
    """
    A class that can iterate over possible permuations
    of the given 'iterable' and 'length' argument.
    """

    def __init__(self, iterable, length):
        self.length = length
        self.current = 0
        self.max = len(iterable) ** length
        self.iterable = iterable

    def __iter__(self):
        return self

    def __next__(self):
        if self.current >= self.max:
            raise StopIteration

        try:
            return permutation_atindex(self.current, self.iterable, self.length)
        finally:
            self.current   += 1

给它一个可迭代的对象和一个整数作为输出长度。

from string import ascii_lowercase

for e in PermutationIterator(ascii_lowercase, 3):
    print "".join(e)

这将从'aaa'开始,以'zzz'结束。

答案 4 :(得分:2)

chars = range(ord('a'), ord('z')+1);
print [chr(a) + chr(b) +chr(c) for a in chars for b in chars for c in chars]

答案 5 :(得分:0)

我们可以通过使用两个函数定义来解决此问题,而无需使用itertools:

def combos(alphas, k):
    l = len(alphas)
    kRecur(alphas, "", l, k)

def KRecur(alphas, prfx, l, k):
    if k==0:
        print(prfx)
    else:
        for i in range(l):
            newPrfx = prfx + alphas[i]
            KRecur(alphas, newPrfx, l, k-1)

这是通过使用两个函数来完成的,以避免重置Alpha的长度,第二个函数自我迭代,直到其k为0为止,以返回该i循环的k-mer。

由Abhinav Ramana在Geeks4Geeks的解决方案中采用

答案 6 :(得分:-1)

print([a+b+c for a in alphabets for b in alphabets for c in alphabets if a !=b and b!=c and c!= a])

这将删除一个字符串中重复的字符

相关问题