473,699 Members | 2,679 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Sorting an Edge List

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')].

I was successful in doing this a while back with a modified bubble sort
algorithm, but now I can't find my own code. Can the list be sorted with a
comparison function or some other way?

Jul 19 '05 #1
5 2107
Anthony D'Agostino, this is my first raw version, it can fail in lots
of ways depending on your input list l (and surely there are better
ways to do it), but it's a start:

.. l = [('A','Y'), ('J','A'), ('Y','J')]
.. pairs = dict(l)
.. result = []
.. key = pairs.iterkeys( ).next()
.. while pairs:
.. val = pairs.pop(key)
.. result.append( (key, val) )
.. key = val
.. print result

Bear hugs,
Bearophie

Jul 19 '05 #2
Sort demands a unique ordering, which isn't present in your case.
You're constructing an Eulerian path. See Fleury's algorithm:

http://en.wikipedia.org/wiki/Eulerian_path

Jul 19 '05 #3
In article <fL************ ********@comcas t.com>,
"Anthony D'Agostino" <ga*******@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? :-)
Jul 19 '05 #4
I found my old bubble sort solution:

=============== =============== ==============
def esort(edges):
while 1:
swaps = 0
for j in range(len(edges )-2):
if edges[j][1] != edges[j+1][0]:
edges[j+1],edges[j+2] = edges[j+2],edges[j+1] # swap
swaps = 1
if swaps == 0: break
return edges

print esort([('A','Y'), ('J','A'), ('Y','J')])
print esort([(5,0), (6, -12), (0,6), (-12, 3)])
=============== =============== ==============

The list can be any length and there will always be multiple valid
solutions, depending on which edge you start with. I'm using this to sort
edges for mesh subdivision. I just thought there might be a more elegant way
to write it.
Jul 19 '05 #5
On Fri, 29 Apr 2005 23:37:39 -0400, "Anthony D'Agostino" <ga*******@dope .comcast.net> wrote:
I found my old bubble sort solution:

============== =============== ===============
def esort(edges):
while 1:
swaps = 0
for j in range(len(edges )-2):
if edges[j][1] != edges[j+1][0]:
edges[j+1],edges[j+2] = edges[j+2],edges[j+1] # swap
swaps = 1
if swaps == 0: break
return edges

print esort([('A','Y'), ('J','A'), ('Y','J')])
print esort([(5,0), (6, -12), (0,6), (-12, 3)])
============== =============== ===============

The list can be any length and there will always be multiple valid
solutions, depending on which edge you start with. I'm using this to sort
edges for mesh subdivision. I just thought there might be a more elegant way
to write it.

This is not tested beyond what you see, but it might give some ideas for
what you want to do. I finds separate sequences if you combine the above into
one, e.g.,

----< dagostinoedges. py >-----------------------------------------------------------
# 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')].
#
import itertools
def connect(edges):
nodes = dict([(e[0], e) for e in edges])
heads = set([e[0] for e in edges])
tails = set([e[1] for e in edges])
starts = heads - tails
out = []
seen = set()
for h in itertools.chain (starts, heads):
curr = nodes[h]
sub = []
while curr not in seen:
sub.append(curr )
seen.add(curr)
curr = nodes.get(curr[1])
if curr is None: break
if sub: out.append(sub)
return out

if __name__ == '__main__':
edges = set([('A','Y'), ('J','A'), ('Y','J'),
(5,0), (6, -12), (0,6), (-12, 3),
('all', 'alone')])
for sub in connect(edges): print sub
------------------------------------------------------------------------------------
Result:

[ 2:54] C:\pywk\clp>py2 4 dagostinoedges. py
[('all', 'alone')]
[(5, 0), (0, 6), (6, -12), (-12, 3)]
[('A', 'Y'), ('Y', 'J'), ('J', 'A')]
Regards,
Bengt Richter
Jul 19 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

16
3382
by: aruna | last post by:
Given a set of integers, how to write a program in C to sort these set of integers using C, given the following conditions a. Do not use arrays b. Do not use any comparison function like if/then or switch-case c. you can use pointers only d. you cannot use any of the loops either.
0
3238
by: Brian Henry | last post by:
Here is another virtual mode example for the .NET 2.0 framework while working with the list view. Since you can not access the items collection of the list view you need to do sorting another way... here is my code on how I did it to help anyone starting out get an idea of how to use virtual mode in ..NET 2.0 Imports CrystalDecisions.CrystalReports.Engine Imports CrystalDecisions.Shared
7
2188
by: apotheos | last post by:
I can't seem to get this nailed down and I thought I'd toss it out there as, by gosh, its got to be something simple I'm missing. I have two different database tables of events that use different schemas. I am using python to collate these records for display. I do this by creating a list of lists that look roughly like this: events = , ...] I then thought I'd just go events.sort(lambda x,y: x<y) and call
17
2790
by: John Salerno | last post by:
Hi everyone. If I have a list of tuples, and each tuple is in the form: (year, text) as in ('1995', 'This is a citation.') How can I sort the list so that they are in chronological order based on the year? Is there a better way to do this than making a list of tuples? (So far I have a text file and on each line is a citation. I use an RE to search for the year, then put this year and the entire citation in a tuple, and add this tuple...
3
1685
by: joeke3el | last post by:
Hi everyone, I have not touched Perl in the last 4 years, my books are at work and I have something here I'm struggling to figure out. From a known list of servers, I need to gather up how many clearcase views are on each server and then only choose the one that has the least number of views that given day. This is what I have so far. my @servers = qw ( srv30bld4 srv30bld5 srv40bld2 srv40bld3 srv40bld4
6
1616
by: aine_canby | last post by:
hi, I have the following list - how do I sort it like this -
2
1508
by: james_027 | last post by:
hi, are there available library or pythonic algorithm for sorting a list of list depending on the index of the list inside the list of my choice? d_list = , , , ,
2
1521
by: Jason | last post by:
Hi folks-- Basically, I have a pressing need for a combination of 5.2 "Sorting a List of Strings Case-Insensitively" & 5.3 "Sorting a List of Objects by an Attribute of the Objects" from the Python Cookbook. My first guess isn't working: import operator def sort_by_attr(seq, attr):
2
5322
by: ihimitsu | last post by:
Hi friends guide me to sorting java list contains multiple list objects
0
8633
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9055
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8902
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7787
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6552
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5891
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4642
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2366
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2016
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.