Python script to generate words from letters and two letter combination

后端 未结 2 751
庸人自扰
庸人自扰 2021-01-29 07:59

I\'m looking to write a short script that will allow me to generate all possible letter combinations with the parameters I set.

For example:

_ _ b _ a

P

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-29 08:53

    I would approach this as follows, using itertools.product in a generator function (to avoid building the whole list unless you absolutely have to):

    from itertools import product
    
    def words(definition):
        for t in product(*definition):
            yield "".join(t)
    

    The only trick is providing the definition in an appropriate format; it must be a list of iterables, each of which provides the options for each "letter". This is easy where each option for a letter is a single character:

    >>> list(words(["f", "o", "aeiou"]))
    ['foa', 'foe', 'foi', 'foo', 'fou']
    

    But with your multiple-character letters you will need to supply a list or tuple:

    >>> list(words([['ph', 'sd', 'nn', 'mm', 'gh'], 
                    ['a', 'e', 'i', 'o', 'u', 'y', 'rc'], 
                    'b', 
                    ['a', 'e', 'i', 'o', 'u', 'y', 'rc'], 
                    'a']))
    ['phabaa', 'phabea', 'phabia', ..., 'ghrcbya', 'ghrcbrca']
    

    Note that in Python 3.3 onwards, this can be done in a single line with yield from:

    def words(definition):
        yield from map("".join, product(*definition))
    

提交回复
热议问题