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.
source to share
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)
source to share
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>
source to share