HackerRank任务Python代码输出异常,请求排查错误
Python列表操作代码错误排查
在HackerRank的Python任务中,代码逻辑接近完成,但运行结果与预期不符:实际输出三次重复最后一个列表且出现None值,与预期输出差异明显,多次调试未找到问题,请求排查错误。
原代码
if __name__ == '__main__': N = int(input()) lst = [] nums = [] for i in range(N): a = input() temp = a.split() if 'insert' in temp: lst.insert(int(temp[1]), int(temp[2])) elif 'print' in temp: nums.append(lst) elif 'remove' in temp: del lst[lst.index(int(temp[1]))] elif 'append' in temp: lst.append(int(temp[1])) elif 'sort' in temp: lst.sort() elif 'pop' in temp: lst.pop(-1) elif 'reverse' in temp: lst = lst.reverse() for i in nums: print(i)
输入示例
12 insert 0 5 insert 1 10 insert 0 6 print remove 6 append 9 append 1 sort print pop reverse print
实际输出
[9, 5, 1] [9, 5, 1] None
预期输出
[6, 5, 10] [1, 5, 9, 10] [9, 5, 1]
错误分析与修正
1. 列表引用导致重复输出
问题出在nums.append(lst):列表是可变对象,直接添加lst到nums中,存储的是列表的引用而非副本。后续对lst的所有修改都会同步影响nums中已添加的元素,最终nums里的所有元素都是lst的最终状态。
修正:改为添加列表的副本,例如:
nums.append(lst.copy()) # 或者 nums.append(list(lst))
2. reverse()方法赋值导致None
lst.reverse()是原地反转列表的方法,返回值为None。原代码中lst = lst.reverse()会把lst直接赋值为None,导致最后一次print输出None。
修正:直接调用方法即可,不需要赋值:
lst.reverse()
修正后的代码
if __name__ == '__main__': N = int(input()) lst = [] nums = [] for i in range(N): a = input() temp = a.split() if 'insert' in temp: lst.insert(int(temp[1]), int(temp[2])) elif 'print' in temp: nums.append(lst.copy()) elif 'remove' in temp: del lst[lst.index(int(temp[1]))] elif 'append' in temp: lst.append(int(temp[1])) elif 'sort' in temp: lst.sort() elif 'pop' in temp: lst.pop(-1) elif 'reverse' in temp: lst.reverse() for i in nums: print(i)
运行修正后的代码,输出将与预期完全一致。
内容的提问来源于stack exchange,提问作者William Gwinell
相关产品推荐
相关产品推荐

