Recursion is one of the most important topics in CSC148.
When Prof Heap first introduced that topic back in week 4, I was amazed and at
the same time, I was confused as well. What is recursion? In plain English
recursion means “define something in terms of itself;” furthermore, in
Programing language recursion means that a function can call itself to solve
smaller sub problems. By looking at the definition, it seems pretty easy to
understand. However, the concept of recursion was abstract for me when I first
encountered it. I took the stubborn approach, which is tried to trace down
every single step of a recursion code, and I thought that was the only way to
understand it. This is where the confused part came in, after few traces I
already felt it is impossible to trace anymore. I knew I was wrong, so I
decided spend some time to fix my understanding about recursion. The result was
good. First I think of an easiest example that does not require a recursive
step. Second I modify the example so that it requires one recursive step. To
phrase it better, I basically think of a base case and then modify it to become
a recursive case, and that is it. No more headaches!
An example to look at is the freeze function which is from the lab I did in week 5, and this function takes an object and returns it. However, if I input a list as a parameter. It will return a copy of the list. so if I modify the old list, the new list will not be modified.
def freeze(X: object) -> object:
"""
>>> freeze('zxcds')
'zxcds'
>>> L1 = [1, [2, 3], 4]
>>> L2 = freeze(L1)
>>> L1 is L2
False
>>> L1 == L2
True
>>> L1[1] == L2[1]
True
"""
if isinstance(X, list):
return [freeze(i) if isinstance(i, list) else i for i in X]
else:
return X
I first think of an non-recursive example say, [1, 2, 3,4]. I use list comprehension to make a copy of the old list.
Then I write the non-recursive part of the code which is "else i for i in X]"
Then I modify the non-recursive example to a recursive one which only includes one recursive step say, [1, [2, 3], 4].
Then I write the recursive part of the code which is " [freeze(i) if isinstance(i, list)."
at index 1 which is a list of [2,3] and is where the recursion begins. "freeze(i)" is called and new list [2, 3] is produced, and a copy of [1, [2, 3], 4] is made.
Recursion is useful once I know how to write it. One base case and one recursive case are crucial for writhing a recursive code.
No comments:
Post a Comment