2014-03-26 4 views
1

예를 찾아서 가까운 예제를 찾았지만이 링크의 대답은 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를 가져온다면 운동의 목적을 물리 칠 수 있습니다.

+0

재귀 적이어야합니까? 그것을 정렬 한 다음 반복 할 수 있습니까? – AndyG

+0

정렬이 잘못되었다고 생각합니다. 그렇지 않으면 그냥 정렬 (집합 (목록)) –

+0

@andyG 예, 재귀 적이어야합니다. –

답변

1
from itertools import groupby 

def remove_dups(lst): 
    return [k for k,items in groupby(lst)] 

, 나는 그것이 시간 문제의 대부분 무언가 목록 재귀를 사용하는 경우

def remove_dups(lst): 
    if lst: 
     firstval = lst[0] 

     # find lowest index of val != firstval 
     for index, value in enumerate(lst): 
      if value != firstval: 
       return [firstval] + remove_dups(lst[index:]) 

     # no such value found 
     return [firstval] 
    else: 
     # empty list 
     return [] 
0

귀하의 주장은 코멘트에 지정된

return thelist 

당신이 사본을 같은 목록을 반환하지 않기 때문에 실패합니다.

보십시오 : 당신이 정말로 재귀 솔루션을 원하는 경우

return thelist[:] 
+0

맞아요, 그렇긴하지만 내가 끝내는 것을 바꾸지 마라. 나는 첫 번째 코드 셋의 마지막 세 줄을 바꿔야한다고 생각한다. –

0

같은 제안 하위 목록이나 그 목록의 일부를 반환합니다. 종료 목록을 빈 목록에 대해 테스트합니다. 그리고 당신은 두 경우가 있습니다

  1. 현재 값은 우리가 현재 값은 우리가 마지막으로 본 하나 우리가 그것을 폐기와 동일한 것이
  2. 을 유지하려는 그래서 마지막으로 본 것과 다른 값의 "나머지"를 계속 반복합니다.

어떤이 코드에서 번역 :

l = [1,2,2,3,3,3,4,5,1,1,1] 

def dedup(values, uniq): 
    # The list of values is empty our work here is done 
    if not values: 
    return uniq 
    # We add a value in 'uniq' for two reasons: 
    # 1/ it is empty and we need to start somewhere 
    # 2/ it is different from the last value that was added 
    if not uniq or values[0] != uniq[-1]: 
    uniq.append(values.pop(0)) 
    return dedup(values, uniq) 
    # We just added the exact same value so we remove it from 'values' and 
    # move to the next iteration 
    return dedup(values[1:], uniq) 

print dedup(l, []) # output: [1, 2, 3, 4, 5, 1] 
+0

철저히 설명해 주셔서 감사합니다. 선들 사이의 의견에 감사드립니다. –

0

에 문제가 return 문 함께,

을 당신이 항상 목록의 N 단일 요소를 지속됩니다

return remove_dups(thelist[i:]) 

출력을 반환하는

위와 같이 곧,

print remove_dups([1,2,2,3,3,3,4,5,1,1,1]) 
>>> [1] #as your desired is [1,2,3,4,5,1] 

마지막으로 Oth 요소를 고려하지 않기 때문에 단일 요소 목록을 반환합니다.

여기는 재귀적인 해결책입니다.

def remove_dups(lst): 
    if len(lst)>1: 

     if lst[0] != lst[1]: 
      return [lst[0]] + remove_dups(lst[1:]) 

     del lst[1] 
     return remove_dups(lst) 
    else: 
     return lst 
+0

네가 맞아! 나는 하나의 가치만을 계속 지켰다. 고맙습니다. –

+0

솔루션에 대한 답변을 편집했습니다. 검토 할 수 있습니다. 나는 그것의 더 나은 해결책을 생각한다. – Roshan

관련 문제