RECURSION
RECURSION
RECURSION
RECURSION
Aren't I bored?
How we met recursion:
"The magic of recursion lies in its ability to perform countless computations with just a few statements."
- Flying Fish (CSC148)
When we were first introduced to the concept of recursion through readings(the one about fractals), I, along with some classmates, found it fairly confusing.
However, I managed to grasp the idea with the help of the fourth lab and more recently, the fifth.
Instructors have defined a recursive function as one that is able to call itself over and over again.
Though if I am to summarize to my best ability in form of analogy, recursion is similar to opening one of those layered gift boxes, which I used in middle school for 'dramatic effects' at my friends' Birthday parties.
Here's the closest picture I can find:
# Mine weren't so fancy; and, I usually prefer to have multiple boxes(or small bags) at one level to make sure my friend will not get to the gift too easily.
Until the gift is found, the recursion can keep calling itself(that is, to continue opening boxes).
To put it in code:
def find_gift(L):
if isinstance(L, gift): # pretend gift is a type in python, just like list and str.
return L
else:
find_gift(x) for x in L
At first, tracing some functions in lab 4 for nested lists was very confusing. However, I later realized what I was doing wrong after consulting my professor during the office hours. Frankly, I usually over traced and spent lots of time because I did not use the traced results from previous steps.
After learning from my mistakes, I had fun tracing more recursive functions!
In lab 5, I wrote list_queue and did tracing on paper.
def list_queue(lst, queue):
for element in lst:
queue.enqueue(element)
while not queue.is_empty():
d = queue.dequeue()
if isinstance(d, list):
list_queue(d, queue)
else:
print(d)
As I drew things in piles on paper, everything came to sense!
For instance, a list such as [1,[3,5],[4,[5,6],8],9]
1 ------> print(1)
[3,5]
[4,[5,6],8]
9 --------> print(9)
3---------> print(3)
5 ----------> print(5)
4-----------> print(4)
[5,6]
8-------------->print(8)
5--------------->print(5)
6----------------->print(6)
---------------------------------------FLYINGFISH's FINISH LINE--------------------------------------------
See you next time! (zzzzzZZZzzzzzz)



No comments:
Post a Comment