python: Convert a for loop into a recursion function

后端 未结 3 1754
死守一世寂寞
死守一世寂寞 2021-01-14 06:46

First of all, I\'m still a newb to python so please take it easy on me.

I\'ve done my research and I have a basic understanding of how to write a recursive function

相关标签:
3条回答
  • 2021-01-14 07:12
    def recurseDict(dictionary):
        if "children" in dictionary:
            return recurseDict(dictionary['children'])
        else:
            return "Whatever you want to return here -- you didn't specify"
    

    This will take a dictionary, check if "children" is one of its keys, then recurse through the dictionary dictionary['children'] and etc etc until it gets to a point where there isn't a 'children' key (e.g. the dictionary has no further branches) where it goes into the else branch and you can return whatever the heck you want -- you didn't specify.

    0 讨论(0)
  • 2021-01-14 07:16

    Here is an example approach to recursively go through a dictionary, assuming that each child is also a dictionary:

    def compute(my_dict):
        if 'children' in my_dict:
            print my_dict['children']
            for child in my_dict['children']:
                compute(child)
    
    0 讨论(0)
  • 2021-01-14 07:24

    I would approach this as follows:

    def recursive(input, output=None):
        if output is None:
            output = {} # container to store results
        if 'children' in input:
            # do whatever, add things to output
            recursive(input['children'], output)
        return output
    

    This way, the output dictionary is accessible to all depths of iteration and gets returned with all contents at the end. This means that you don't have to explicitly deal with the return values of the recursive calls.

    Depending on exactly what you have, it may look more like:

    def recursive(input, output=None):
        if output is None:
            output = {} # container to store results
        if 'children' in input:
            for child in input['children']:
                # do whatever, add things to output
                recursive(child, output)
        return output    
    

    And output may be a different container (e.g. list, set).

    0 讨论(0)
提交回复
热议问题