2014-10-28 5 views
0

재귀를 사용하여이 동일한 함수를 작성하려면 어떻게해야합니까? 내가 원래의 복사본을 만들하기로하고 거기에서 목록에서 =을 (B)을,하지만 난 그것을 구현하는 방법을 모르는거야 생각재귀를 사용하여 목록 반복

def replace(thelist,a,b): 
"""Returns: a COPY of thelist but with all occurrences of a replaced by b. 

    Example: replace([1,2,3,1], 1, 4) = [4,2,3,4]. 

Precondition: thelist is a list of ints 
       a and b are ints""" 

. 이 문제를 해결할 수 있도록 도와주세요. 감사합니다.

+0

왜 재귀를 이용해야합니까? – Andy

+0

아직 시도해 보셨나요? 몇 가지 코드를 보여주십시오. [:] newlist가 == [] 경우 : 복귀 0 복귀 (A = B가 newlist [0]는 그 밖에 == 경우) + 대체 (newlist – Austin

+1

이 문제가 재귀 – steve12

답변

0

이 시도 :

def replace(thelist, a, b): 
    if not thelist: 
     return [] 
    elif thelist[0] == a: 
     return [b] + replace(thelist[1:], a, b) 
    else: 
     return [thelist[0]] + replace(thelist[1:], a, b) 

을 그것은 재귀 솔루션, 그리고 예상대로 작동합니다

replace([1, 2, 3, 1], 1, 4) 
=> [4, 2, 3, 4] 
관련 문제