Sorting an Edge List

Roy Smith roy at panix.com
Fri Apr 29 18:12:58 EDT 2005


In article <fLqdne0t4Y81OO_fRVn-qw at comcast.com>,
 "Anthony D'Agostino" <gamma-ray at dope.comcast.net> wrote:

> I need to sort this list:
> [('A','Y'), ('J','A'), ('Y','J')] like this:
> [('A','Y'), ('Y','J'), ('J','A')].
> 
> Note how the Ys and Js are together. All I need is for the second element of 
> one tuple to equal the first element of the next tuple. Another valid 
> solution is [('J','A'), ('A','Y'), ('Y','J')].

This is an interesting problem.  Can you give us more details?  I'm 
assuming the length of the list can be any arbitrary length.  Will there 
always only be three letters?  Can there ever be a pair with the same first 
and second elements, i.e. ('A', 'A')?

Will there always be a valid solution?  For example, it's trivial to show 
that

[('A', 'Y'), ('A', 'J'), ('J', 'A')]

cannot be sorted using your criteria (there's no pair starting with 'Y' to 
match the one that ends with 'Y')

Is this a real-life problem, or are we doing your homework for you? :-)



More information about the Python-list mailing list