How can I return values ​​to a recursive function without stopping the recursion?

I have a structure with x number of lists in lists and each list x number of tuples. I don't know in advance how many nested lists there are or how many tuples there are in each list.

I want to make dictionaries from all tuples and because I do not know the depth of the lists that I want to use for recursion. What I did was

def tupleToDict(listOfList, dictList):
    itemDict = getItems(list)  # a function that makes a dictionary out of all the tuples in list
    dictList.append(itemDict)
    for nestedList in listOfList:
         getAllNestedItems(nestedList, dictList)

    return dictList

      

this works, but in the end I end up with a huge list. I would rather return itemDict in every round of recursion. However, I don't know how (if possible) to return the value without stopping the recursion.

+3


source to share


4 answers


You are looking for yield

:

def tupleToDict(listOfList):
    yield getItems(listofList)
    for nestedList in listOfList:
        for el in getAllNestedItems(nestedList):
            yield el

      

In Python 3.3+, you can replace the last two lines yield from

.



You can rewrite your function as iterative:

def tupleToDict(listOfList):
    q = [listOfList]
    while q:
        l = q.pop()
        yield getItems(l)
        for nestedList in listOfList:
            q += getAllNestedItems(nestedList)

      

+6


source


Who are you going to return it to? I mean, if your thread is busy running a recursive algorithm that gets "intermediate results" for processing?



Your best bet is to tweak your algorithm to enable some processing before it gets repeated again.

+1


source


I'm not sure what you are trying to do, but you can try to create a recursive generator using the yield statement to return the dict at the desired intervals. Either that or copy it to the global list?

+1


source


You have two possible solutions:

  • Generator approach: a function with a yield statement, which can be a problem to implement in a recursive function. (See the phihags example sentence for an example)

  • Callback approach: you call a helper function / method from within the recursion and can track progress through a second outer function.

Here's an example of non-recursive recursion :; -)

def callback(data): print "from the depths of recursion: {0}".format(data)

def recursion(arg, callbackfunc):
    arg += 1
    callbackfunc(arg)
    if arg <10:
        recursion(arg, callbackfunc)
    return arg

print recursion(1, callback)

      

code>

+1


source







All Articles