如何生成dwww格式的数字与大写字母组合?修正递归代码问题
问题:修正生成dwww格式数字大写字母组合的Python代码
需求:生成所有符合**dwww(数字-大写字母-大写字母-大写字母)**格式的字符组合,但以下代码输出不符合目标格式,需修改:
upper_a = ['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'] num = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] all = num + upper_a def recursive_product(myList, length, myString = ""): if length == 0: print (myString) with open('TDH-H.txt', 'a') as the_file: the_file.writelines('{}\n'.format('TDH-H' + str(myString))) return for c in myList: recursive_product(myList, length-1, myString + c) for r in range(4, 5): code = recursive_product(all, r)
问题分析
原代码的核心问题是:使用num + upper_a的混合列表生成所有4位组合,导致结果会出现字母开头、中间穿插数字的情况,完全不符合第一位必须是数字,后三位必须是大写字母的dwww格式要求。
修正方案
方案1:使用itertools.product(更简洁高效)
直接利用标准库的笛卡尔积生成工具,明确区分第一位(数字)和后三位(大写字母):
import itertools upper_a = ['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'] num = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] # 生成所有组合:第一位是数字,后三位是大写字母 with open('TDH-H.txt', 'w') as the_file: # 用'w'覆盖文件,避免多次运行重复写入 for digit in num: for chars in itertools.product(upper_a, repeat=3): combo = digit + ''.join(chars) print(combo) the_file.write(f'TDH-H{combo}\n')
方案2:修改原递归函数
如果坚持用递归实现,拆分逻辑:第一位单独遍历数字,递归仅生成后三位的大写字母组合:
upper_a = ['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'] num = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] def generate_three_chars(length, current=""): if length == 0: return [current] result = [] for c in upper_a: result.extend(generate_three_chars(length-1, current + c)) return result # 打开文件写入 with open('TDH-H.txt', 'w') as the_file: three_char_combos = generate_three_chars(3) for digit in num: for combo in three_char_combos: full_combo = digit + combo print(full_combo) the_file.write(f'TDH-H{full_combo}\n')
内容的提问来源于stack exchange,提问作者Mohammad Jafari
相关产品推荐
相关产品推荐

