Coursera作业:move_zero函数测试失败,AssertionError问题求助
解决move_zero函数的AssertionError问题
你的代码存在几个核心问题,导致测试报错:
- 违反函数要求:题目明确要求函数无返回值,但你的代码最后
return k,这直接触发了assert_equal(None, move_zero(lst))的断言错误——函数返回了排序后的列表而非None。 - 逻辑完全偏离需求:把列表转成字符串拆解的方式会破坏多位数(比如输入
[10,0]会被拆成[1,0,0]),而且通过取最小值排序的操作,改变了非零元素的原始顺序。题目要求非零元素保持原来的相对位置,仅将零移至末尾。 - 错误处理输入:测试外的
input("user input: ")会得到字符串而非整数列表,不符合作业测试的调用方式。
修正后的代码
def move_zero(lst): """ Given a list of integers, moves all non-zero numbers to the beginning of the list and moves all zeros to the end of the list. This function returns nothing and changes the given list itself. For example: - After calling move_zero([0,1,0,2,0,3,0,4]), the given list should be [1,2,3,4,0,0,0,0] and the function returns nothing - After calling move_zero([0,1,2,0,1]), the given list should be [1,2,1,0,0] and the function returns nothing - After calling move_zero([1,2,3,4,5,6,7,8]), the given list should be [1,2,3,4,5,6,7,8] and the function returns nothing - After calling move_zero([]), the given list should be [] and the function returns nothing """ # 统计列表中零的数量 zero_count = lst.count(0) # 提取所有非零元素,保留原始顺序 non_zero_elements = [num for num in lst if num != 0] # 清空原列表,重新填充非零元素+对应数量的零 lst.clear() lst.extend(non_zero_elements) lst.extend([0] * zero_count) # 测试示例 test_lst = [0,1,0,2,0,3,0,4] move_zero(test_lst) print(test_lst) # 输出: [1,2,3,4,0,0,0,0]
代码逻辑说明
- 用
lst.count(0)统计零的个数,方便后续批量补充。 - 列表推导式提取非零元素,完全保留它们的原始相对顺序。
- 通过
clear()清空原列表,再用extend()依次添加非零元素和对应数量的零,直接修改原列表,符合题目“直接修改原列表、无返回值”的要求。
内容的提问来源于stack exchange,提问作者serge
相关产品推荐
相关产品推荐

