Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

I want to make dictionaries out of all the tuples and because I don't know the depth of the lists I want to use 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 I end up with a huge list at the end. I would rather return the itemDict at every round of recursion. However, I don't know how to (if it is possible) return a value without stopping the recursion.

like image 732
Niek de Klein Avatar asked Jul 05 '26 13:07

Niek de Klein


2 Answers

You're 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 with a yield from.

You may want to rewrite your function to be iterative:

def tupleToDict(listOfList):
    q = [listOfList]
    while q:
        l = q.pop()
        yield getItems(l)
        for nestedList in listOfList:
            q += getAllNestedItems(nestedList)
like image 96
phihag Avatar answered Jul 07 '26 03:07

phihag


Who are you going to return it to? I mean if your thread is busy running the recursive algorithm, who gets the "interim results" to process?

Best bet is to tweak your algorithm to include some processing before it recurses again.

like image 36
John3136 Avatar answered Jul 07 '26 04:07

John3136



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!