正确生成单词而不重复

你能用 26 个字母的字母表组成多少个 5 个字母的单词(不重复)?我正在编写一个程序,它可以从 5 个字母生成名称(只是单词),格式为:辅音_元音_一致_元音_辅音。只有5个字母。拉丁语。我只是想了解我必须运行生成周期多少次。例如,在 65780 处,重复已经开始。你能告诉我如何正确地做吗?


import random

import xlsxwriter


consonants = ['B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q',

              'R', 'S', 'T', 'V', 'W', 'X', 'Z']


vowels = ['A', 'E', 'I', 'O', 'U', 'Y']


workbook = xlsxwriter.Workbook('GeneratedNames.xlsx')

worksheet = workbook.add_worksheet()



def names_generator(size=5, chars=consonants + vowels):

    for y in range(65780):

        toggle = True

        _id = ""

        for i in range(size):

            if toggle:

                toggle = False

                _id += random.choice(consonants)

            else:

                toggle = True

                _id += random.choice(vowels)

        worksheet.write(y, 0, _id)

        print(_id)

    workbook.close()



names_generator()


潇潇雨雨
浏览 147回答 4
4回答

慕无忌1623718

您可以使用itertools.combinations来获取 3 个不同的辅音和 2 个不同的元音,并获取permutations它们来生成所有可能的“名称”。from itertools import combinations, permutationsnames = [a+b+c+d+e for cons in combinations(consonants, 3)                   for a, c, e in permutations(cons)                   for vow in combinations(vowels, 2)                   for b, d in permutations(vow)]总共只有 205,200 = 20x19x18x6x5,因此对于 5 个字母来说根本不需要时间,但对于更多字母来说很快就会花费更长的时间。也就是说,如果“不重复”是指任何字母都不应出现超过一次。相反,如果您只是希望不重复连续的字母(这已经通过交替辅音和元音来保证),或者不重复名称(通过不随机地构造它们来保证),您可以itertools.product使用总共 288,000 个 = 20x20x20x6x6 名称:names = [a+b+c+d+e for a, c, e in product(consonants, repeat=3)                   for b, d in product(vowels, repeat=2)]如果您想以随机顺序生成它们,您可以只random.shuffle在后面列出列表,或者如果您只想要几个这样的名称,您可以在结果列表上使用random.sample或。random.choice

扬帆大鱼

如果你想避免重复,你不应该使用随机性,而只是生成所有这样的 ID:from itertools import productC = consonantsV = vowelsfor id_ in map(''.join, product(C, V, C, V, C)):    print(id_)或者from itertools import cycle, islice, productfor id_ in map(''.join, product(*islice(cycle((consonants, vowels)), 5))):    print(id_)

温温酱

itertools 允许非重复排列import itertools, renames = list(itertools.product(consonants + vowels, repeat=5))consonants_regex = "(" + "|".join(consonants) + ")"vowels_regex = "(" + "|".join(vowels) + ")"search_string = consonants_regex + vowels_regex + consonants_regex + vowels_regex + consonants_regexnames_format = ["".join(name) for name in names if re.match(search_string, "".join(name))]  输出:>>> len(names)11881376>>> len(names_format)288000

慕森王

我想确保回答你的问题我只是想了解我必须运行生成周期多少次因为我认为对问题有更好的直觉很重要。您有 20 个辅音和 6 个元音,总共产生 20x6x20x6x20 = 288000 种不同的单词组合。由于它是连续的,因此您可以将其拆分以使其更易于理解。您可以将 20 个不同的辅音作为第一个字母,然后为每一个添加 6 个元音 = 20x6 = 120。然后您可以继续说,对于这 120 个组合,您可以为每个组合添加 20 个辅音 = 120x20 = 2400 。 .. 等等。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python