Question

Algorithm to reduce a list of hierarchically-named items

Asked by: jdpipe

Hi all,

I think this is a pretty interesting algorithm problem so I'll post a link under 'programming' as well. But I'm hoping for a python solution, so it's going to live here.

I have a list of items like this, *as strings*.

C.x
C.p
C.T
C.delta[1]
C.delta[2]
C.delta[3]
C.sat.x
C.sat.p
C.h
C.delta[5]

and I would like to convert that into something more readable, like

C: x, p, T, delta[1-3,5], h
C.sat: x, p

* values in brackets can be numbers, in which case they can be assumed integers, and sequences of integers should be condensed like [1,2,3,5] to [1-3,5]
* values in brackets can also be 'symbols', in which case they are just listed out, eg [symbol1, symbol2, symbol3].
* brackets can act as a suffix for any node, not just the final one
* nodes are either array member nodes like x in "A[1]", or symbol nodes, like "A[symbol1]" or named nodes, like "A.x".
* the algorithm should zipper together as much as possible, as shown

Optional: it would be cool if

A.x[1].p
A.x[2].p

could be output as "A: x[1-2].p". Obviously this makes the problem quite a bit harder.

I thought that it might be possible to tackle this using python's list.reduce(func) method. But I haven't had any luck yet. The only way this is going to be solvable seems to be to re-construct the 'tree' then reduce it somehow with a top-down approach of some sort.

Cheers
JP



This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2006-02-01 at 21:55:45ID21719649
Tags

python

,

algorithm

Topic

Python Scripting Language

Participating Experts
2
Points
500
Comments
11

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Algorithms
    Suggest sites where i can find an index to algorithms for all possible programs.....(almost all)
  2. Cryptographic algorithms
    I need a site where a can find good reference (informations) about Cryptographic algorithms especialy: DES, IDEA, RSA, Merkle-Hellman I whant to make the code but for this i have to understand the algorithms.
  3. Vectorization algorithm?
    I have some raster imagery (already pretty blocky) and I would like to vectorize them. I am not looking for an application like Corel Trace, etc, but instead the actual algorithms that I can use to clean-up and vectorize a raster image into polygon areas prpgramatically... i...
  4. Algorithms
    I'm looking for two algorithms to work under VBA 1. A Set Covering algorithm, 2. Max. Independent Set or Max Clique algorithm 500 points for each working algorithm Thanks,
  5. Voronoi algorithm in Python
    See http://www.experts-exchange.com/Programming/Programming_Languages/Python/Q_21057314.html The sum of points is now 1000 for somebody brave enough.
  6. algorithms
    can someone tell me the names ( and possible locations of java source code) or some algorithms that are good for finding suggestions for words that may be misspelled. for example there are 'edit-distance' algorithms, the levehnstein algorithm....but i need more that may hel...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: anthrax759Posted on 2006-02-02 at 11:17:20ID: 15856012

I can offer a suggestion as to how you'd do this... first and foremost, you'll want to loop entirely through each string and create an entry for it... I'd suggest having a switch statement that catches any numerical value and sets it aside into that category.. then letter values and sets them aside in that category... then catch the open bracket [ and anything up until the close bracket ] and repeat the process for each term, and even separate the terms by . so for example have a data structure with a sub1,2,3,4,5,etc and bkt1,2,3,4,5,etc and num1,2,3,4,5,etc.
We could take this:
C.x[12].pqzed.o
and as it looped through, it would be stored as follows:
C -> it's a letter, store it in sub1 then check next value
. -> it's a dot, so we'll take it as a separation
x -> it's a letter, so store it in sub2 and check next value
[ -> ooh it's a bracket, so we store not only the letter before it but also the element(s) inside it as well as the number itself in
] -> end the bracket
. -> next term
p -> letter, check next...
q -> letter, check next...
z -> letter, check next...
e -> letter, check next...
d -> letter, check next...
. -> terminate the last string and start new...
o -> letter, end of term...
Archive the term and start fresh for the next one...
Once you've achieved this, you'll want to do data comparisons...
Check each of the sub-terms to see if they're the same or at least similar, differing only by numbers... and if so, order the numbers...
As for the 1-7, that's a simple counting algorithm... compare the numerical values, and increment to see if they're in sequence... if so, continue until that sequence is broken, and once it's broken you have the starting term and the term that breaks the cycle(minus one) and just separate them with a dash... then, continue for the rest of them... I could probably write this up in a day or two although I write in C/C++ more than Python...

I hope this helps.
-aNthrax

 

by: jdpipePosted on 2006-02-02 at 16:47:08ID: 15858959

Hi anthrax,

You've explained the issue of string parsing the lines here but that's really not the part I have a problem with. I can do this with simple regexps or DParser or something. The tough part is the "data comparisons" part, and that is the only part I am struggling to conceptualise properly. I really think that one needs to construct a tree and then traverse it in a clever way. But this is the part that I'm looking for input on.

Cheers
JP

 

by: anthrax759Posted on 2006-02-02 at 19:07:00ID: 15859767

Well, as a native C++ programmer, I use strstr() or strcmp() for string comparisons... I'm not sure as to how to do it through Python... I'll do a little research and get back to you some time this weekend.

 

by: jdpipePosted on 2006-02-02 at 19:32:59ID: 15859886

Cool, thanks for this. Hope you find it interesting, too.

 

by: mish33Posted on 2006-02-07 at 10:50:02ID: 15895191

from itertools import groupby
from operator import itemgetter

def fold(data):
    """ fold sorted numeric sequence data into ranged representation:
    >>> fold([1,  4,5,6, 10, 15,16,17,18, 22, 25,26,27,28])
    '[1,4-6,10,15-18,22,25-28]'
    """
    folded = []
    for k, g in groupby(enumerate(data), lambda (i,x):i-x):
        seq = map(itemgetter(1), g)
        if len(seq) > 1:
            x = '%s-%s' % (seq[0], seq[-1])
        else:
            x = str(seq[0])
        folded.append(x)
    return folded and '[%s]' % ','.join(folded) or ''

def reduce(names):
    """reduce a list of items nto something more readable:
    >>> data = 'C.x C.p C.T C.delta[1] C.delta[2] C.delta[3] C.sat.x C.sat.p C.h C.delta[5]'.split()
    >>> res = reduce(data)
    >>> for k in sorted(res):
    ...   print '%s: %s' % (k, res[k])
    C: T, delta[1-3,5], h, p, x
    C.sat: p, x
    """
    data = sorted([n.split('.') for n in names], key=len)
    res = {}
    for k, g in groupby(data, lambda x: len(x)):
        item = g.next()
        assert len(item) == k
        key = '.'.join(item[:-1])
        indexed = {}
        seq = set(get(indexed, item))
        for item in g:
            seq.add(get(indexed, item))
        res[key] = ', '.join(i+fold(indexed.get(i, [])) for i in sorted(seq))
    return res

def get(indexed, item):
    item = item[-1]
    if item.endswith(']'):
        item, idx = item[:-1].split('[')
        indexed.setdefault(item, []).append(int(idx))
    return item

Enjoy!

 

by: jdpipePosted on 2006-02-07 at 16:30:25ID: 15898417

Hi Mish33, thanks very much, a very nicely-written solution!

 

by: jdpipePosted on 2006-02-08 at 00:10:14ID: 15900402

Hi Mish,

Have just been trying your suggestion out now. I have a minor problem though, mostly due to my example not being general enough. In some cases, my list will look like this:
Sl.phirdelta_r2[49]
Sl.phirdelta_r2[50]
Sl.phirdelta_r2[51]
Sl.dPSI_ddelta[56]
Sl.DELTA[56]
Sl.tau
rhof
rhol
T
Sl.delta
Sl.d1

As you can see, there are multiple root nodes in this list, eg 'rhof', 'rhol', 'T'. It seems to be a possibility that isn't handled by your code, and the code ends up splitting strings into characters in this case. Any suggestions for a quick fix on this?

Cheers
JP

 

by: mish33Posted on 2006-02-08 at 05:18:44ID: 15902003

Sure. Change two lines inside reduce for loop to:

        key = '.'.join(item[:-1]) or ''
        seq = set([get(indexed, item)])

Global names will be grouped under ''. Put whatever name you want (eg. 'GLOBAL') instead of ''.

 

by: jdpipePosted on 2006-02-08 at 23:22:41ID: 15910509

Cool, that works well, thanks

JP

 

by: jdpipePosted on 2006-02-08 at 23:54:03ID: 15910589

Hmm seems that there is still a bug actually. Tried it with the following:

S2.d1
S2.rho
S2.t1
S2.phi0tau
S2.phirtau_r2[8]
S2.phirtau_r2[9]
S2.phirtau_r2[10]
S2.phirtau_r2[11]
S2.phirtau_r2[12]
S2.phirtau_r2[13]
S2.phirtau_r2[14]
S2.phirtau_r2[15]
S2.phirtau_r2[16]
S2.phirtau_r2[17]
S2.phirtau_r2[18]
S2.phirtau_r2[19]
S2.phirtau_r2[20]
S2.phirtau_r2[21]
S2.phirtau_r2[22]
S2.phirtau_r2[23]
S2.phirtau_r2[24]
S2.phirtau_r2[25]
S2.phirtau_r2[26]
S2.phirtau_r2[27]
S2.phirtau_r2[28]
S2.phirtau_r2[29]
S2.phirtau_r2[30]
S2.phirtau_r2[31]
S2.phirtau_r2[32]
S2.phirtau_r2[33]
S2.phirtau_r2[34]
S2.phirtau_r2[35]
S2.phirtau_r2[36]
S2.phirtau_r2[37]
S2.phirtau_r2[38]
S2.phirtau_r2[39]
S2.phirtau_r2[40]
S2.phirtau_r2[41]
S2.phirtau_r2[42]
S2.phirtau_r2[43]
S2.phirtau_r2[44]
S2.phirtau_r2[45]
S2.phirtau_r2[46]
S2.phirtau_r2[47]
S2.phirtau_r2[48]
S2.phirtau_r2[49]
S2.phirtau_r2[50]
S2.phirtau_r2[51]
S2.phirdelta_r2[9]
S2.phirdelta_r2[10]
S2.phirdelta_r2[11]
S2.phirdelta_r2[12]
S2.phirdelta_r2[13]
S2.phirdelta_r2[14]
S2.phirdelta_r2[15]
S2.phirdelta_r2[16]
S2.phirdelta_r2[17]
S2.phirdelta_r2[18]
S2.phirdelta_r2[19]
S2.phirdelta_r2[20]
S2.phirdelta_r2[21]
S2.phirdelta_r2[22]
S2.phirdelta_r2[23]
S2.phirdelta_r2[24]
S2.phirdelta_r2[25]
S2.phirdelta_r2[26]
S2.phirdelta_r2[27]
S2.phirdelta_r2[28]
S2.phirdelta_r2[29]
S2.phirdelta_r2[30]
S2.phirdelta_r2[31]
S2.phirdelta_r2[32]
S2.phirdelta_r2[33]
S2.phirdelta_r2[34]
S2.phirdelta_r2[35]
S2.phirdelta_r2[36]
S2.phirdelta_r2[37]
S2.phirdelta_r2[38]
S2.phirdelta_r2[39]
S2.phirdelta_r2[40]
S2.phirdelta_r2[41]
S2.phirdelta_r2[42]
S2.phirdelta_r2[43]
S2.phirdelta_r2[44]
S2.phirdelta_r2[45]
S2.phirdelta_r2[46]
S2.phirdelta_r2[47]
S2.phirdelta_r2[48]
S2.phirdelta_r2[49]
S2.phirdelta_r2[50]
S2.phirdelta_r2[51]
S2.r3_b1[52]
S2.r3_b1[53]
S2.r3_b1[54]
S2.PSI[55]
S2.dPSI_dtau[55]
S2.dPSI_ddelta[55]
S2.theta[55]
S2.dDELTA_ddelta[55]
S2.DELTA[55]
S2.dDELTAbi_ddelta[55]
S2.dDELTAbi_dtau[55]
S2.theta[56]
S2.dDELTA_ddelta[56]
S2.DELTA[56]
S2.dDELTAbi_ddelta[56]
S2.dDELTAbi_dtau[56]
S2.PSI[56]
S2.dPSI_dtau[56]
S2.dPSI_ddelta[56]
T_ho
C.DT_2
S2.phirdelta
C.LMTD
q
C.h_h2
S2.phirdelta_r2[8]
S2.phirtau
S2.tau
S2.delta

and I got the entry 'LMTD' showing up under 'S2'. Any further thoughts?

 

by: mish33Posted on 2006-02-09 at 08:56:00ID: 15914382

Sorry about that. Replace fold() and reduce() with

def fold(data):
    """ fold sorted numeric sequence data into ranged representation:
    >>> fold([1,  4,5,6, 10, 15,16,17,18, 22, 25,26,27,28])
    '[1,4-6,10,15-18,22,25-28]'
    """
    folded = []
    for k, g in groupby(enumerate(sorted(data)), lambda (i,x):i-x):
        seq = map(itemgetter(1), g)
        if len(seq) > 1:
            x = '%s-%s' % (seq[0], seq[-1])
        else:
            x = str(seq[0])
        folded.append(x)
    return folded and '[%s]' % ','.join(folded) or ''

def reduce(names):
    """reduce a list of items nto something more readable:
    >>> data = 'C.x C.p C.T C.delta[1] C.delta[2] C.delta[3] C.sat.x C.sat.p C.h C.delta[5]'.split()
    >>> res = reduce(data)
    >>> for k in sorted(res):
    ...   print '%s: %s' % (k, res[k])
    C: T, delta[1-3,5], h, p, x
    C.sat: p, x
    """
    data = sorted([n.split('.') for n in sorted(names)], key=len)
    res = {}
    for k, g in groupby(data, lambda x: len(x)):
        if k == 1:
            indexed = {}
            seq = set(get(indexed, item) for item in g)
            res['[global]'] = ', '.join(i+fold(indexed.get(i, [])) for i in sorted(seq))
        else:
            for key, g1 in groupby(g, lambda x: '.'.join(x[:-1])):
                indexed = {}
                seq = set(get(indexed, item) for item in g1)
                res[key] = ', '.join(i+fold(indexed.get(i, [])) for i in sorted(seq))
    return res

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...