[Tutor] Sorting against another list

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Fri, 22 Jun 2001 00:42:54 -0700 (PDT)


On Fri, 22 Jun 2001, Sharriff Aina wrote:

> I have a list that is created dynamically, how do I sort this list so that
> it matches amother "mater template" list?
> 
> example:
> [ 'aa', 'qq', 'ttt', 'hh']  # master list
> 
> my dynamic list cotains all or only a few of the elements in the master
> list:
> 
> ['ttt', 'hh', 'aa'] ### i would like to sort it to produce ['aa''ttt',
> 'hh']  accoriding to the sequense in the master list
> 
> or [ 'hh', 'qq' 'ttt'] ### would like ['qq', 'ttt', 'hh']
>  
> I would like to sort these example list so that they at least follow the
> order of the master list.


Question: are we assuming that the dynamic list contains only elements
from the master list?  If so, then here's one idea to do this sort:

###
def myDirectedSort(master_list, dynamic_list):
    sorted_list = []
    for element in master_list:
        if element in dynamic_list:
            sorted_list.append(element)
    return sorted_list
###

Here's the idea of this function: let's march down the master list.  If
the element that we're looking at is in the dynamic list, it should
definitely be part of our sorted list.  By marching down the master list
in order, we're making sure that the sorted_list is always sorted relative
to the master list.  When we're done, we end up with a sorted list whose
elements must have come out of the dynamic_list.


This function assumes, however, that the dynamic_list is always a "subset"
of the master_list: it will break if we try something like this:

    s = myDirectedSort([1, 2, 3, 4], [3, 2, 2])

In this case, the myDirectedSort will not do the right thing, since there
are more '2's in the dynamic_list than in the master_list.

Hope this helps!