The below coding is a simple example of recursion with tracing a recursion. It is also an example I practiced during this week's lab.
def count_elements(L):
’’’(list or non-list) -> int
Return 1 if L is a non-list, or number of non-list elements in
possibly-nested list L.
Assume: L is any Python object.
>>> count_element([1,2,3]) #usually two examples are required.
3
>>> count_elements('Hello') # L is non-list.
1
>>> count_elements('Hello') # L is non-list.
1
’’’
if isinstance(L, list): # if L is a list
return sum([count_elements(x) for x in L])
else: # if L is not a list, count it
return 1
Example of Tracing using above examples. Note that return replaces with "-->" sign.
count_elements([1,2,3])
--> sum([count_elements(x) for x in L]) # since L is a list
--> sum([count_elements(1), count_elements(2), count_elements(3)]) # use of recursion
--> sum([1, 1, 1])
--> 3
count_elements('Hello')
--> 1 # since L is not a list, this function simply returns 1.
To review what I learnt this week, I will do more practice on recursion problems. Furthermore, for upcoming term test 1, I need to go over extra questions provided by professor for the lab. For first few weeks, I got to learn various things about coding including class inheritance, subclass, and data abstract. The most difficult part I found during the first few weeks is the class inheritance using a subclass. At first, I didn't understand why I have to use raise NotImplementedError("subclass needed"), However, now with assignment 1 and many practices during a lab, I was able to get how the class inheritance can be useful for a programmer. The most interesting study I found so far is the use of recursion how it is able to call the function itself to analyze the nested list. I hope I can learn more things about coding through CSC148.
Overall, I think that enough practices and effort make this course a lot easier and enjoyable. I hope someone in the future who will take CSC148 would be able to read my advice. As for other people's SLOG, I read quite a few of them, and most of SLOG entries were finely done and interesting. So I think later on I will probably post some of SLOG links which I find useful and interesting.
Overall, I think that enough practices and effort make this course a lot easier and enjoyable. I hope someone in the future who will take CSC148 would be able to read my advice. As for other people's SLOG, I read quite a few of them, and most of SLOG entries were finely done and interesting. So I think later on I will probably post some of SLOG links which I find useful and interesting.