To use it correctly, there must exist a very clear way to end the recursion or it would just call itself again and again and will never end. For example, this function:
def nested_concat(L):
’’’(list or str) -> str
Return L if it’s a str, if L is a (possibly-nested) str return
concatenation of str elements of L and (possibly-nested) sublists of L.
Assume: Elements of L are either str or lists with elements that
satisfy this same assumption.
’’’
if isinstance(L, str):
return L
else:
return ’’.join([nested_concat(x) for x in L])
In this function, the return L is a example of clear way to end the recursion. Once the list of str, list of str, list of str have been all run, it will simply return the string to end the recursion.
However, recursion may be quite time-consuming if dealing with a huge data. This may cause the stack over-loading the data. To change this, I must learn more in python.
No comments:
Post a Comment