所以我几乎完成了这项功课,但只有在我弄清楚为什么这么做之后 当我以递归方式调用它时,这个循环不会继续。
我将以一个名字作为输入并将他的孩子和父亲作为输出返回。
例如,Kanky的孩子是撒旦,malan,ulan,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 :(得分: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