I'm trying to solve the following exercise from Google's Python class.
E. Given two lists sorted in increasing order, create and return a merged list of all the elements in sorted order. You may modify the passed in lists. Ideally, the solution should work in "linear" time, making a single pass of both lists.
I'm using the following Scheme approach (I wish I had car, cdr and cons!).
def helper(list1, list2, result):
if list1 == None:
return result + list2
elif list2 == None:
return result + list1
elif list1[0] < list2[0]:
return helper(list1[1:], list2, result.insert(0, list1[0]))
else:
return helper(list1, list2[1:], result.insert(0, list2[0]))
def linear_merge(list1, list2):
helper(list1, list2, [])
The error I get is, I can't seem to insert an element into result when result is []:
AttributeError: 'NoneType' object has no attribute 'insert'
But that works fine in the console:
>>> b = []
[]
>>> b.insert(0, 4)
>>> b
[4]
I'm brand new to Python, so I have two questions:
- What am I missing about None vs. [], and how do I get this code to work?
- If Python wasn't meant for a Scheme/Lisp approach, what's the "Python way" of solving this? This is less important to me, since I can just check the solutions.
Thanks!
Nonewithis, not==. But that's not your problem here.list.insertmodifies the list in-place, and returnsNone. So you probably don't want to pass it as a parameter for a function.car,cdr, andconsfor Python lists, that's pretty easy:def car(xs): return xs[0],def cdr(xs): return xs[1:],def cons(x, xs): return [x] + xs. But again,cdrandconswill be linear time. If you really want to use Scheme algorithms without thinking about them, build an actualConstype (which is very easy) and use that. Or, better, rethink your algorithm to work from the right, or to work in terms of passing a list and a slice object instead of slicing the list, or…