Python数组处理程序输出异常求助:去重结果不符预期
问题排查与解决方案
问题原因
你的代码实现的是常规去重逻辑(每个重复数字仅保留首次出现的实例),但结合示例输入的预期输出来看,题目实际要求的是移除所有出现次数≥2的数字,仅保留只出现过一次的数字。
以示例输入为例:
计算得到的updated_A数组为 [6, 9, 5, 15, 15],其中数字15出现了两次。你的代码去重后会保留15,而预期输出需要完全移除这类重复出现的数字,只留下出现次数唯一的6、9、5。
解决方案
修改逻辑,先统计每个数字的出现次数,再筛选出仅出现一次的数字。以下是两种实现方式:
方式一:基础实现(不依赖外部库)
def keep_unique_only(arr): # 统计每个数字的出现次数 count = {} for num in arr: count[num] = count.get(num, 0) + 1 # 按原顺序筛选仅出现一次的数字,避免重复添加 result = [] seen = set() for num in arr: if count[num] == 1 and num not in seen: result.append(num) seen.add(num) return result N = int(input("Enter the size of the arrays: ")) A = list(map(int, input("Enter the elements of array A: ").split())) B = list(map(int, input("Enter the elements of array B: ").split())) updated_A = [A[B[i]] + A[i] for i in range(N)] result = keep_unique_only(updated_A) print("Numbers after removing duplicates:", end=" ") print(' '.join(map(str, result)))
方式二:使用collections.Counter简化统计
from collections import Counter N = int(input("Enter the size of the arrays: ")) A = list(map(int, input("Enter the elements of array A: ").split())) B = list(map(int, input("Enter the elements of array B: ").split())) updated_A = [A[B[i]] + A[i] for i in range(N)] num_counts = Counter(updated_A) # 筛选仅出现一次的数字并保持原顺序 result = [] seen = set() for num in updated_A: if num_counts[num] == 1 and num not in seen: result.append(num) seen.add(num) print("Numbers after removing duplicates:", end=" ") print(' '.join(map(str, result)))
验证结果
运行示例输入:
Enter the size of the arrays: 5 Enter the elements of array A: 1 5 4 7 8 Enter the elements of array B: 1 2 0 4 3
输出为:Numbers after removing duplicates: 6 9 5,与预期一致。
内容的提问来源于stack exchange,提问作者user3521180
相关产品推荐
相关产品推荐

