You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python生成大小写变体及无重复排列:求更优雅高效的实现方案

需求描述

给定单词列表与字符列表,需完成以下操作:

  • 为每个单词生成四种大小写变体:全小写、全大写、首字母大写、首字母小写其余大写
  • 生成所有可能的递增排列(即长度从1到所有元素总数的排列)
  • 排列中需避免大小写不敏感的重复——同一排列里不能同时包含同一原单词的不同大小写变体(比如不能同时出现one和One)

示例

输入

words = ["one", "two"]
chars = ["!"]

生成的单词变体

one, One, ONE, oNE, two, Two, TWO, tWO

有效排列示例

one, one!, !one, One, One!, !One, ONE, ONE!, !ONE, two, two! ...,
...onetwo, onetwo!, !onetwo, Onetwo, Onetwo!, !Onetwo, ...
...OneTwo, OneTwo!, !OneTwo, ...
...twoone, twoone!, !twoone, ...etc.

无效排列示例

oneOne, oneONE, oneoNE, ...twoTwo, twoTWO, twotWO...

原始实现代码

import itertools

words = ["one", "two"]
chars = ["2022", "!", "_"]

file_permuted = "permuted_words.txt"

transformed_words = []
words_to_permute = []
permuted_words = []
counter = 0
total_counter = 0

for word in words:
    # 生成四种大小写变体:全小写、全大写、首字母大写、首字母小写其余大写
    lowercase_all = word.lower()
    uppercase_all = word.upper()
    capitalize_first = word.capitalize()
    toggle_case = capitalize_first.swapcase()

    # 添加到变体列表
    transformed_words.append(lowercase_all)
    transformed_words.append(uppercase_all)
    transformed_words.append(capitalize_first)
    transformed_words.append(toggle_case)

words_to_permute = transformed_words + chars

print("Generating permutations...")
with open(file_permuted, "w") as f:
    for i in range(1, len(words_to_permute) + 1):
        for permutation in itertools.permutations(words_to_permute, i):
            # 检查排列中是否有大小写不敏感的重复
            len_set_permutation = len(set(list(map(lambda x: x.lower(), permutation))))
            if len_set_permutation == len(permutation):
                f.write("".join(permutation) + "\n")
                if counter == 100:
                    total_counter += counter
                    print(f'Processed {total_counter} items')
                    counter = 0
                counter += 1

优化实现方案

思路说明

原始代码的核心问题是先生成所有可能元素再过滤无效排列,会产生大量冗余计算。优化思路改为:

  1. 将每个原单词的变体归为一组,每个字符单独作为独立组(字符无大小写冲突,可任意组合)
  2. 先选择合法的元素组合(从不同组中选取元素,确保不会出现同一原单词的不同变体)
  3. 对每个合法组合生成所有排列,直接输出有效结果

这种方式从根源上避免了无效排列的生成,大幅提升效率,同时代码结构更清晰。

优化代码

import itertools

words = ["one", "two"]
chars = ["2022", "!", "_"]
file_permuted = "permuted_words.txt"

# 构建分组:每个原单词对应一组大小写变体,每个字符单独成组
groups = []
# 添加单词变体组
for word in words:
    variants = [
        word.lower(),
        word.upper(),
        word.capitalize(),
        word.capitalize().swapcase()
    ]
    groups.append(variants)
# 添加字符组
for char in chars:
    groups.append([char])

counter = 0
total_counter = 0

print("Generating permutations...")
with open(file_permuted, "w") as f:
    # 遍历所有可能的组合长度(1到总组数)
    for combo_length in range(1, len(groups) + 1):
        # 选择combo_length个不同的组
        for selected_groups in itertools.combinations(groups, combo_length):
            # 从每个选中的组里选一个元素,生成所有可能的元素组合
            for elements in itertools.product(*selected_groups):
                # 对当前元素组合生成所有排列
                for perm in itertools.permutations(elements):
                    f.write("".join(perm) + "\n")
                    counter += 1
                    if counter == 100:
                        total_counter += counter
                        print(f'Processed {total_counter} items')
                        counter = 0
    # 处理剩余未统计的计数
    if counter > 0:
        total_counter += counter
        print(f'Processed {total_counter} items')

优化点说明

  • 效率提升:通过分组选择的方式,直接跳过无效组合,避免了原代码中大量无效排列的生成与过滤操作
  • 结构清晰:将变体生成、分组选择、排列生成的逻辑拆分,代码可读性更强
  • 计数完善:补充了循环结束后剩余计数的统计,避免遗漏

内容的提问来源于stack exchange,提问作者CyberLuke365

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 05:21:57