After an awesome week of
reading break, week 7 was totally stressful and tense. I had 4 tests in 3 days
in a roll…… I would never want that to happen ever again…… :( Luckily, that was all finished.
Since week 4 ish, the
professor already started to discuss about recursion with us in lectures. Recursion
was something new to all of us; to think of writing codes that would use itself
as part of the codes over and over again was novelty and cool to me at first.
According to http://dictionary.reference.com,
recursion is defined as:
“the process of defining a function or calculating a number by the repeated application of an algorithm.”
In
python, as far as we have learnt, we have seen functions which they call other
functions in the same (or imported) files. Recursions is basic to call python’s
ability for a function to call itself.
It was kind of hard to
imagine what it is when the professor just introduced this topic, yet he showed
us a function called rec_max: it find the maximum number in the nested list
from the input. This is a pretty typical example for recursion. The function
would look through all the nested lists within the input to make sure that the
number it returns would be the biggest of all:
Another thing that the prof
brought up a very interesting function, “Turtle”. Sorry that I could not find a
correct image for the visualization of “Turtle”. Yet I found a similar one to
demonstrate what does the code do:
We first set the speed and
the color of the pathway of the turtle when we initialize it from class Turtle.
Then, we input how many levels (recursions) and base (length of the pathway). Basically,
if level equals to 1, the turtle would just draw 3 lines in 3 directions (120o
apart from each other) with 3 different colors of the base’s length. If the equals
to 2, the turtle would add another half of the lengths and draw 3 more branches
with 3 lines the turtle drew when the level equals to 1. I made some pictures
from level 1 to level 4:
As
one can see, as the input of the level gets larger, the resulting picture will
slowly form a huge triangle.
In sum, recursion is just a
smart trick for the programmers to use when they have to deal with nested
things (lists, tuples etc.) or situations that would involve in break it down to
tons of smaller pieces.
No comments:
Post a Comment