因此,我几乎完成了这项作业,但只有在弄清楚为什么会这样做之后
当我递归调用时,此循环不会继续.
我将以名字作为输入,并返回他的孩子和父亲作为输出.
例如,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 :(
解决方法:
老实说,我不想分析您的代码以查找问题所在,但我知道如何正确执行.
看一下这个:
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