递归可缩减最长英文单词程序问题排查及修正咨询
问题分析与代码修改方案
差异原因
- 验证逻辑不完整:你的代码可能没有遍历所有字母删除路径,导致
complecting这类存在有效缩减路径的单词被误判为不符合条件。比如仅验证了部分子词路径,而非所有可能路径。 - 终止条件偏差:题目要求最终缩减至单个有效单词,若你的代码错误限定了终止单字母(比如默认必须是a/i,但
words.txt不含这两个字母),会漏掉符合条件的单词;或者未正确判断单字母是否在有效集合中。 - 最长单词筛选逻辑错误:若
complecting长度(10个字母)比你输出的单词(均为9个字母)更长,你的代码可能未优先选择长度最长的单词,而是返回了所有同长的符合条件单词。 - 单词集合加载问题:若
words.txt包含complecting,但加载时未统一大小写、未去除换行符等,会导致该单词未被纳入有效集合,无法被识别。
代码修改方案
1. 修复递归验证逻辑
确保遍历所有可能的字母删除路径,只要存在一条能缩减到有效单字母的路径,就判定单词符合条件:
def is_reducible(word, word_set): # 终止条件:单字母且在有效集合中 if len(word) == 1: return word in word_set # 遍历每个位置的字母删除情况 for idx in range(len(word)): sub_word = word[:idx] + word[idx+1:] # 子词有效且可继续缩减时,返回True if sub_word in word_set and is_reducible(sub_word, word_set): return True return False
2. 优化最长单词筛选逻辑
遍历单词时动态记录最长的符合条件单词,长度相同时可保留全部:
def find_longest_reducible_words(word_list): word_set = set(word_list) max_len = 0 longest_candidates = [] for word in word_list: if is_reducible(word, word_set): current_len = len(word) if current_len > max_len: max_len = current_len longest_candidates = [word] elif current_len == max_len: longest_candidates.append(word) return longest_candidates
3. 修正单词集合加载
加载words.txt时统一处理大小写和空白字符,避免匹配错误:
# 加载单词列表 with open('words.txt', 'r') as f: valid_words = [line.strip().lower() for line in f if line.strip()] # 执行查找 result = find_longest_reducible_words(valid_words) print(', '.join(result))
4. 确认终止条件匹配要求
检查words.txt中的单字母单词,确保终止条件正确——只要单字母在word_set中,就视为有效终止,无需额外限定(比如a/i)。
内容的提问来源于stack exchange,提问作者Aniket Harit
相关产品推荐
相关产品推荐

