递归提取列表重复项代码不符合需求,求问题排查与修正
递归查找重复项代码的问题分析
需求说明
需要实现一个递归函数,找出列表中所有重复项,按原顺序生成每个重复元素仅出现一次的新列表:
- 输入
[1,2,2,3,3,3,4,4,4,4],输出[2,3,4] - 输入
[1,2,24,2,1],输出[1,2]
原代码
def find_duplicates(list_of_numbers): #start writing your code here dup_list=[] if len(list_of_numbers) < 1: dup_list=[] else: if list_of_numbers[0] in list_of_numbers[1:]: print(list_of_numbers[0]) dup_list=[list_of_numbers[0]]+find_duplicates(list_of_numbers[1:]) else: dup_list=find_duplicates(list_of_numbers[1:]) return dup_list list_of_numbers=[1,2,2,3,3,3,4,4,4,4] list_of_duplicates=find_duplicates(list_of_numbers) print(list_of_duplicates)
代码存在的问题
- 重复元素多次添加:原逻辑只要当前元素在剩余列表中存在,就直接加入结果,但后续递归遇到相同元素时,只要该元素仍在剩余列表里,就会再次添加。比如第一个测试用例中,3会被加入两次,4会被加入三次,最终输出
[2,3,3,4,4,4],不符合“每个重复元素仅出现一次”的要求。 - 缺少已记录重复项的跟踪机制:没有判断当前元素是否已经被标记为重复项,导致同一重复元素被多次写入结果列表。
修正后的递归代码
def find_duplicates(list_of_numbers, seen_duplicates=None): # 初始化已记录的重复项列表 if seen_duplicates is None: seen_duplicates = [] # 递归终止条件:列表为空则返回空列表 if not list_of_numbers: return [] current = list_of_numbers[0] remaining = list_of_numbers[1:] # 仅当当前元素后续还有出现,且未被记录过重复时,才加入结果 if current in remaining and current not in seen_duplicates: seen_duplicates.append(current) return [current] + find_duplicates(remaining, seen_duplicates) else: return find_duplicates(remaining, seen_duplicates) # 测试用例1 list1 = [1,2,2,3,3,3,4,4,4,4] print(find_duplicates(list1)) # 输出: [2, 3, 4] # 测试用例2 list2 = [1,2,24,2,1] print(find_duplicates(list2)) # 输出: [1, 2]
修正说明
- 新增
seen_duplicates参数跟踪已确认的重复元素,避免同一元素多次加入结果。 - 调整判断逻辑:只有当前元素在剩余列表中存在且未被记录为重复项时,才将其加入结果列表。
- 简化递归终止条件的写法,用
not list_of_numbers替代len(list_of_numbers) < 1,更符合Python风格。
内容的提问来源于stack exchange,提问作者Diptee S
相关产品推荐
相关产品推荐

