我擡起頭,發現一個很接近的例子,但在這個鏈接中找到的答案: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是的,它必須是遞歸的 –