HackerRank Set的discard/remove/pop挑战代码平台与本地输出不一致
集合操作代码本地与HackerRank结果不一致排查
挑战要求
给定非空集合s,需执行N条pop、remove、discard命令。
输入格式
- 第一行:集合s的元素个数n
- 第二行:n个非负整数(≤9),构成集合s
- 第三行:命令条数N
- 后续N行:每条命令为pop、remove或discard(部分带参数)
问题现象
本地IDE运行测试输入时输出4(符合预期),但在HackerRank平台上输出6,不符合要求。
测试输入
9 1 2 3 4 5 6 7 8 9 10 pop remove 9 discard 9 discard 8 remove 7 pop discard 6 remove 5 pop discard 5
我的代码
input() s = set(map(int, input().split())) num_commands = int(input()) command = ["", ""] for i in range(num_commands): command = input().split() if len(command) == 1: getattr(s, command[0])() elif len(command) == 2: command[1] = int(command[1]) if command[1] in s: getattr(s, command[0])(command[1]) print(sum(s))
错误原因及修正
核心问题
你给remove命令额外添加了if command[1] in s:的存在性判断,这违反了题目对remove命令的要求:必须严格执行remove操作,题目保证输入的remove命令参数一定存在于集合中,无需额外判断。
当集合中的元素被pop提前删除时,你的代码会跳过对应的remove命令,导致少执行一次删除操作,最终集合的求和结果偏大。
比如测试输入中,若第6次pop恰好弹出了5,后续执行remove 5时,你的代码会因为5不在集合中跳过该命令,而正确逻辑是题目保证此时5仍在集合中,必须执行remove(若出现元素不存在的情况,题目会保证输入合法,不会出现这种场景)。
修正后的代码
去掉remove命令的存在性判断,直接执行命令:
input() s = set(map(int, input().split())) num_commands = int(input()) for _ in range(num_commands): command = input().split() if len(command) == 1: getattr(s, command[0])() else: getattr(s, command[0])(int(command[1])) print(sum(s))
或者更直观的分支写法:
input() s = set(map(int, input().split())) num_commands = int(input()) for _ in range(num_commands): parts = input().split() if parts[0] == 'pop': s.pop() elif parts[0] == 'remove': s.remove(int(parts[1])) elif parts[0] == 'discard': s.discard(int(parts[1])) print(sum(s))
内容的提问来源于stack exchange,提问作者David Willis
相关产品推荐
相关产品推荐

