2012-01-04 4 views
3

그래서이 숙제는 거의 끝났지 만, 왜 내가 도대체 ​​뭔지 알아 낸 후에는 반복적으로 호출 할 때이 루프가 계속되지 않는다.재귀 루프가 실패하면 다음 항목으로 진행하지 않습니까?

입력으로 이름을 사용하고 자녀와 아버지를 출력으로 반환합니다.

예를 들어, Kanky의 아이들은 yugi 사탄, 마란 울란이다
과 사탄의 아이들은 벤 & 앨런 있습니다
마란, 내 나무는이 같은 자식 보인다 없다 :

T=["Kanky",["satan",["ben","ian"],"Alan"],"malan",["yugi","yuppi"]] 

내 코드 :

def find_the_man(T,name): 

    F = tree[0]  # the head of list 
    C = tree[1:] # tail of the list 
    kids = ""  # find the kids and append to this str 
    if F==name: 
     i = 0 
     while i<len(C): 
      #do some things to find the children 
      #return them 


    for i in C:  ### this loop tries to find the man with no child 
     if i==name: 
      return [daddy,notfound] ### if it finds, returns it 

    for i in C:    ### this is my whole thing, it takes just the 
     if type(i)==list: ### first list(unfortenately), if it finds the 
      find_the_man(i,name) ### man by doing the actions on top, 
     else:continue    ### it returns the child, but it is not able to 
           ### proceed the next lists, so when i give an input 
return [notfound,notfound] ### like (T,"yugi"), it gives notfound :(
+0

그래서 당신은 그 루프()'기능을 당신의'find_the_man를 호출하지만, 결과 아무것도 아닙니다. 왜 그렇게 부르죠? 어쩌면 결과 목록을 작성하고 그 결과를 반환해야할까요? – kindall

+0

실제로는 무언가를하고 있지만 처음 중첩 된 루프의 경우 해당 목록에서 찾지 못하면 원하는대로 다음 목록으로 진행할 수 없습니다 .. 어떤 경우 결과 목록을 작성해야합니까? 그 남자의 아이들을 찾아내는 것이 더 힘들겠습니까? – Karavana

+2

아마도'return find_the_man (i, name)'을 원할 것입니다. 이것은 일반적인 재귀 적 전략 (정기적으로 보거나 사용하는 유일한 전략)입니다. 그렇지 않으면 재귀는 아무 것도하지 않습니다 ... 이미 무시되었습니다. – FakeRainBrigand

답변

3

솔직히 말해서 문제를 찾는 데 코드를 분석하고 싶지는 않지만 올바르게 수행하는 방법을 알고 있습니다.

확인이 아웃 :

def find_the_man(T, name, p = None): 
    r = False 
    for i in T: 
     if type(i) == list: 
      r = find_the_man(i, name, T[0]) 
      if r: 
       break 
     elif i == name: 
      return (p, [ i[0] if type(i) == list else i for i in T[ 1: ] ]) if T.index(i) == 0 else (T[0], None) 
    return r 

T= [ "Kanky", [ "satan", [ "ben", "ian" ], "Alan" ], "malan", [ "yugi", "yuppi" ] ] 
# function return tuple (parent, list_of_children) 
find_the_man(T, "Kanky") # (None, ['satan', 'malan', 'yugi']) 
find_the_man(T, "satan") # ('Kanky', ['ben', 'Alan']) 
find_the_man(T, "ben") # ('satan', ['ian']) 
find_the_man(T, "malan") # ('Kanky', None) 
find_the_man(T, "yugi") # ('Kanky', ['yuppi']) 
find_the_man(T, "yuppi") # ('yugi', None) 
find_the_man(T, "stranger")# False 
관련 문제