简体   繁体   English

列出所有可能的字母为n的单词

[英]List all possible words with n letters

I want to list all possible words with n letters where the first letter can be a1 or a2, the second can be b1, b2 or b3, the third can be c1 or c2, ... Here's a simple example input-output for n=2 with each letter having 2 alternatives: 我想列出所有具有n个字母的单词,其中第一个字母可以是a1或a2,第二个可以是b1,b2或b3,第三个可以是c1或c2,...这是n的简单输入输出示例= 2,每个字母有2个选择:

  • input = [["a","b"],["c","d"]] 输入= [[“ a”,“ b”],[“ c”,“ d”]]
  • output = ["ac", "ad", "bc", "bd"] 输出= [“ ac”,“ ad”,“ bc”,“ bd”]

I tried doing this recursively by creating all possible words with the first 2 letters first, so something like this: 我尝试通过先创建前两个字母的所有可能单词来递归地执行此操作,如下所示:

def go(l):
    if len(l) > 2:
        head = go(l[0:2])
        tail = l[2:]
        tail.insert(0, head)
        go(tail)
    elif len(l) == 2:
        res = []
        for i in l[0]:
            for j in l[1]:
                res.append(i+j)
        return res
    elif len(l) == 1:
        return l
    else:
        return None

However, this becomes incredibly slow for large n or many alternatives per letter. 但是,对于每个字母较大的n或许多替代项,这变得非常慢。 What would be a more efficient way to solve this? 有什么更有效的方法来解决这个问题?

Thanks 谢谢

I think you just want itertools.product here: 我认为您只想在这里itertools.product

>>> from itertools import product
>>> lst = ['ab', 'c', 'de']
>>> words = product(*lst)
>>> list(words)
[('a', 'c', 'd'), ('a', 'c', 'e'), ('b', 'c', 'd'), ('b', 'c', 'e')]`

Or, if you wanted them joined into words: 或者,如果您希望它们加入单词中:

>>> [''.join(word) for word in product(*lst)]
['acd', 'ace', 'bcd', 'bce']

Or, with your example: 或者,以您的示例为例:

>>> lst = [["a","b"],["c","d"]]
>>> [''.join(word) for word in product(*lst)]
['ac', 'ad', 'bc', 'bd']

Of course for very large n or very large sets of letters (size m ), this will be slow. 当然,对于非常大的n或非常大的字母集(大小m ),这很慢。 If you want to generate an exponentially large set of outputs ( O(m**n) ), that will take exponential time. 如果要生成一组指数较大的输出( O(m**n) ),则将花费指数时间。 But at least it has constant rather than exponential space (it generates one product at a time, instead of a giant list of all of them), and will be faster than what you were on your way to by a decent constant factor, and it's a whole lot simpler and harder to get wrong. 但是至少它具有恒定的空间而不是指数空间(它一次生成一个产品,而不是所有产品的庞大列表),并且以相当的恒定因子比您要达到的速度更快,并且更容易出错。

You can use the permutations from the built-in itertools module to achieve this, like so 您可以使用内置itertools模块中的permutations来实现此目的,就像这样

>>> from itertools import permutations
>>> [''.join(word) for word in permutations('abc', 2)]
['ab', 'ac', 'ba', 'bc', 'ca', 'cb']

Generating all strings of some length with given alphabet : 用给定的字母生成一定长度的所有字符串:

test.py : test.py:

def generate_random_list(alphabet, length):
    if length == 0: return []
    c = [[a] for a in alphabet[:]]
    if length == 1: return c
    c = [[x,y] for x in alphabet for y in alphabet]
    if length == 2: return c
    for l in range(2, length):
        c = [[x]+y for x in alphabet for y in c]
    return c

if __name__ == "__main__":
    for p in generate_random_list(['h','i'],2):
        print p

$ python2 test.py $ python2 test.py

['h', 'h']
['h', 'i']
['i', 'h']
['i', 'i']

Next Way : 下一步:

def generate_random_list(alphabet, length):
    c = []
    for i in range(length):
        c = [[x]+y for x in alphabet for y in c or [[]]]
    return c

if __name__ == "__main__":
    for p in generate_random_list(['h','i'],2):
        print p

Next Way : 下一步:

import itertools
if __name__ == "__main__":
    chars = "hi"
    count = 2
    for item in itertools.product(chars, repeat=count):
        print("".join(item))

import itertools
print([''.join(x) for x in itertools.product('hi',repeat=2)])

Next Way : 下一步:

from itertools import product
#from string import ascii_letters, digits

#for i in product(ascii_letters + digits, repeat=2):
for i in product("hi",repeat=2):
    print(''.join(i))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 给定字典和字母列表,找到可以用字母创建的所有可能单词 - Given a Dictionary and a list of letters, find all possible words that can be created with the letters 删除列表中单词末尾的\\ n及后面的字母 - Delete the \n and following letters in the end of words in a list 从列表字母中打印所有可能的长度为 10 的单词的组合,其中重复“A”两次 - Print all possible combination of words of length 10 from a list letters with repeating 'A' exactly twice 从给定的单词列表中生成具有“N”长度的所有可能组合(寻找不重复) - Generate all possible combination with “N” length from given words list (Looking for no repeat) 生成所有可能的字母“模式”列表 - Generate a list of all possible "patterns" of letters 正则表达式获取具有特定字母的所有单词列表(unicode字形) - Regex to get list of all words with specific letters (unicode graphemes) 提取所有可能的 n-gram (n = 1, 2),将连字词视为单个词 - Extract all possible n-grams (n = 1, 2), considering hyphenated words as single words 快速查找单词列表是否包含至少一个以某些字母开头的单词(不是“查找所有单词”!) - Fast way to find if list of words contains at least one word that starts with certain letters (not "find ALL words"!) 将嵌套列表中的单词拆分为字母 - Split words in a nested list into letters 列表中包含连续重复字母的单词 - Words in a list with consecutively repeated letters
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM