ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

递归循环是否失败到下一个项目?

2019-12-01 23:55:50  阅读:198  来源: 互联网

标签:loops python recursion


因此,我几乎完成了这项作业,但只有在弄清楚为什么会这样做之后
当我递归调用时,此循环不会继续.

我将以名字作为输入,并返回他的孩子和父亲作为输出.

例如,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

标签:loops,python,recursion
来源: https://codeday.me/bug/20191201/2084385.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有