I had a task like this. The section in this chapter called Alice in Wonderland, again! started with the observation that the merge algorithm uses a pattern that can be reused in other situations. Adapt the merge algorithm to write each of these functions, as was suggested there:
I need to solve this: a. Return only those items that are present in both lists.
The merge algorithm is given like this:
def merge(xs, ys):
""" merge sorted lists xs and ys. Return a sorted result """
result = []
xi = 0
yi = 0
while True:
if xi >= len(xs): # If xs list is finished,
result.extend(ys[yi:]) # Add remaining items from ys
return result # And we're done.
if yi >= len(ys): # Same again, but swap roles
result.extend(xs[xi:])
return result
# Both lists still have items, copy smaller item to result.
if xs[xi] <= ys[yi]:
result.append(xs[xi])
xi += 1
else:
result.append(ys[yi])
yi += 1
My way off solving this question is:
def merge(xs, ys):
""" merge sorted lists xs and ys. Return a sorted result """
result = []
xi = 0
yi = 0
while True:
if xi >= len(xs): # If xs list is finished,
return result # And we're done.
if yi >= len(ys): # Same again, but swap roles
return result
for xi in xs:
if xi in ys:
result.append(xi)
xs = [1,3,4,5,7,9,11,13,15,17,19]
ys = [4,5,8,12,16,20,24]
zs = xs+ys
zs.sort()
print(merge(xs, ys))
If you are interested in more information about this question you can find here: http://openbookproject.net/thinkcs/python/english3e/list_algorithms.html
The most important question for me: is there a better way off doing it and if there is, can you guys point me to the right direction?