我抬起头,发现一个很接近的例子,但在这个链接中找到的答案:Remove adjacent duplicate elements from a list将不会运行这个问题的测试用例。所以这是我到目前为止有:递归删除列表中的相邻副本
def remove_dups(thelist):
"""Returns: a COPY of thelist with adjacent duplicates removed.
Example: for thelist = [1,2,2,3,3,3,4,5,1,1,1],
the answer is [1,2,3,4,5,1]
Precondition: thelist is a list of ints"""
i = 1
if len(thelist) == 0:
return []
elif len(thelist) == 1:
return thelist
elif thelist[i] == thelist[i-1]:
del thelist[i]
return remove_dups(thelist[i:])
def test_remove_dups():
assert_equals([], remove_dups([]))
assert_equals([3], remove_dups([3,3]))
assert_equals([4], remove_dups([4]))
assert_equals([5], remove_dups([5, 5]))
assert_equals([1,2,3,4,5,1], remove_dups([1,2,2,3,3,3,4,5,1,1,1]))
# test for whether the code is really returning a copy of the original list
mylist = [3]
assert_equals(False, mylist is remove_dups(mylist))
编辑,同时我也明白,上面用itertools.groupby将工作挂钩接受的答案,我想会不会教我什么是错我的代码&并会如果我从itertools中导入了grouby,就会击败练习的目的。
它必须是递归的吗?你能排序它,然后迭代它吗? – AndyG
我会认为排序是错误的,否则你只是做排序(设置(列表)) –
@andyG是的,它必须是递归的 –