如何编写符合测试要求的Python列表元素移除remove()函数?
How to Implement Python's
remove() Function for Specific List Element Removal Got it, let's break down what we need to do here to get this remove() function passing all the test cases. First, let's look at what the tests are expecting:
When we remove an element at position pos:
- All elements after
posshould shift left by one position to fill the gap - The list should keep its original length, with the last position replaced by
None
The Solution Code
Here's the implementation that will satisfy all the test assertions:
def remove(lst: list, pos: int): # Shift elements after the target position left by one for i in range(pos, len(lst) - 1): lst[i] = lst[i + 1] # Set the last element to None to maintain list length lst[-1] = None
How It Works
Let's walk through this with the test cases to see why it works:
- First test case: We start with a 6-element list and remove index 2. The loop runs from
pos=2tolen(lst)-2=4(sincerangeis exclusive on the upper bound). Each element from index 2 to 4 gets replaced by the element to its right. Then we set the last element (index 5) toNone—exactly what the assertion expects. - Second test case: Removing index 0 from a 3-element list. The loop runs from 0 to 1, shifting elements 1 and 2 left to fill index 0 and 1. Then we set index 2 to
None, resulting in[10, 15, None]. - Third test case: Removing the only element in a 1-element list. The loop doesn't run at all (since
len(lst)-1=0,range(0,0)is empty), so we just set the single element toNone, matching the assertion.
If you run the test_remove() function with this implementation, all assertions will pass.
内容的提问来源于stack exchange,提问作者user9486126
相关产品推荐
相关产品推荐

