troubleshooting Question

# Algorithm to reduce a list of hierarchically-named items

Python
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

Join the community to see this answer!
###### Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.