예를 찾아서 가까운 예제를 찾았지만이 링크의 대답은 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 예, 재귀 적이어야합니다. –