46 votes

Quelle est la meilleure façon de générer toutes les chaînes de trois lettres possibles ?

Je génère tous les mots-clés possibles à trois lettres e.g. aaa, aab, aac.... zzy, zzz ci-dessous est mon code :

 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)

Cette fonctionnalité peut-elle être réalisée de manière plus élégante et efficace ?

18voto

gnibbler Points 103484

Vous pouvez également utiliser map au lieu de la compréhension de liste (c'est l'un des cas où map est toujours plus rapide que le LC)

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

Cette variation de la compréhension de la liste est également plus rapide que l'utilisation de ''.join

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

5voto

Asterisk Points 1646
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

4voto

Niklas R Points 2269

Vous pouvez également le faire sans aucun module externe en effectuant un calcul simple. Le PermutationIterator est ce que vous recherchez.

 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

Donnez-lui un objet itérable et un entier comme longueur de sortie.

 from string import ascii_lowercase

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

Cela commencera à partir de « aaa » et se terminera par « zzz ».

2voto

davidvino Points 21
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]

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X