It’s been a big week for CSC148. There are a lot of things I’d like to talk about including the assignment, the test, recursion, and the marking scheme vote. I will comment on the marking scheme vote in an unofficial additional post immediately after this one in which I will discuss recursion.
RECURSION:
I understand recursion in theory but when attempting to implement a recursive function, my brain’s Python Visualizer gets very confused and I kind of end up guessing at things.
I managed to build a recursive list flattener (for any depth) as well as a recursive function to find any particular fibonacci number (revolutionary I know).
For the list flattener, I came up with a couple ways to do it.
First, and probably best (if it must be recursive), is to pass a list as the only argument, then build a new list within the function like so:
def break_list(list_):
flat = []
for item in list_:
if not isinstance(item, list):
flat.append(item)
else:
flat.extend(break_list(item))
return flat
Slightly more complicatedly, you can pass the empty list as a second argument in the function like so:
def break_list2(list_, empty_list=[]):
for item in list_:
if type(item) != list:
empty_list.append(item)
else:
break_list2(item, empty_list)
return empty_list
What I find fancy here is that rather than extending the list with the sublist, we are passing the list that we’re building back into the recursive function as the second argument. I then tried to do this using a list comprehension to build the new list… I don’t know if it’s possible, because it seems as though I would require an if: else statement which I don’t think can be done in a list comprehension. In a hilarious attempt to flatten with list comprehention, I managed to make it just add additional list brackets around items like so:
>>> break_list3([1, 2, 3, [4, [5]]])
[[[1], [2], [3], [[[4], [[[5]]]]]]]
I must have deleted the code unfortunately, because I’m curious what I did.
Bottom line is that recursion requires extra brain power, but so do list comprehensions (since the word ordering is in some way reversed from a regular loop). Doing both at the same time? Let’s wait until I master both techniques individually first.j
Oh and he’s fib. Super simple and kinda looks like it does what it should do, right? Still took a few tries to get it right though.
def fib(x):
if x > 1:
return fib(x-1) + fib(x-2)
elif x == 1:
return 1
elif x == 0:
return 0