Well, I just saw on the course website that we need to write our impression on tracing recursion, I hope it's not too late.Recursion, an interesting idea, which requires a good thinking and can simplify the loops by a lot. It's much like looking at yourself in mirrors and get repetitive image. The thinking process, namely the tracing, is important in recursion, since the language here is a lot more concise.
below is a brief example of recursion shown in practical
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.
# examples omitted!
’’’
if isinstance(L, str):
return L
else: # L is a possibly-nested list of str
return ’’.join([nested_concat(x) for x in L])
- nested_concat(’five’) --> ’five’ # since isinstance(’five’, str)
-
nested_concat([]) --> ’’.join([nested_concat(x) for x in []])
--> ’’.join([]) # there are no x in [] --> ’’ # that’s what join does to empty list nested_concat([’how’, ’now’, ’brown’])--> ’’.join([nested_concat(x) for x in [’how’, ’now’, ’brown’]])--> ’’.join([’how’, ’now’, ’brown’]) # traced nested_concat(str) before --> ’hownowbrown’ # join does ’how’ + ’now’ + ’brown’-
nested_concat([[’how’, [’now’, ’brown’], ’cow’]])
--> ’’.join([nested_concat(x) for x in [’how’, [’now’, ’brown’], ’cow’]) --> ’’.join([’how’, ’nowbrown’, ’cow’]) # traced nested_concat(list of str)# and nested_concat(str) before--> ’hownowbrowncow’ -
nested_concat([[’how’, [’now’, ’brown’, [’cow’]], ’eh?’]])
--> ’’.join([nested_concat(x) for x in [[’how’, [’now’, ’brown’, [’cow’]], ’eh?’]] --> ’’.join([’how’, ’nowbrowncoweh?’]) # believe docstring for str and possibly-nested# list of str or possibly-nested...--> ’hownowbrowncoweh?’When I first saw this example in practical, I raised a question. While tracing the 5th example, is put join([’how’, ’nowbrowncoweh?’]). which I think is wrong, and it turned out that I was right. Our course materials sometimes also make mistakes, eh?
through the tracing process, it is also important to remember not to trace too much, just simply use the result from before, otherwise the tracing will be so long... well, that's the difference between a computer and a human brain, we don't want to make things complex and that's why we developed computer programs.
So long, Ciao!
Dark Fox
Ps: don't forget tp keep track of the brackets while tracing, and make sure what type of object you are using!
No comments:
Post a Comment