David Cramer
David Cramer

Reputation: 1998

Obtain all subtrees in value

Given "a.b.c.d.e" I want to obtain all subtrees, efficiently, e.g. "b.c.d.e" and "c.d.e", but not "a.d.e" or "b.c.d".

Real world situation:

I have foo.bar.baz.example.com and I want all possible subdomain trees.

Upvotes: 2

Views: 170

Answers (4)

pyfunc
pyfunc

Reputation: 66739

Not sure, if this is what you want.

But slicing of the list with varying sizes yields that.

>>> x = "a.b.c.d.e"
>>> k = x.split('.')
>>> k
['a', 'b', 'c', 'd', 'e']
>>> l = []
>>> for el in range(len(k)): l.append(k[el+1:])
... 
>>> l
[['b', 'c', 'd', 'e'], ['c', 'd', 'e'], ['d', 'e'], ['e'], []]
>>> [".".join(l1) for l1 in l if l1]
['b.c.d.e', 'c.d.e', 'd.e', 'e']
>>> 

Of course, the above was to illustrate the process. You could combine them into one liner.

[Edit: I thought the answer is same as any here and explains it well]

Upvotes: 0

khachik
khachik

Reputation: 28703

items = data.split('.')
['.'.join(items[i:]) for i in range(0, len(items))]

Upvotes: 3

nmichaels
nmichaels

Reputation: 51039

listed = "a.b.c.d.e".split('.')
subtrees = ['.'.join(listed[idx:]) for idx in xrange(len(listed))]

Given your sample data, subtrees equals ['a.b.c.d.e', 'b.c.d.e', 'c.d.e', 'd.e', 'e'].

Upvotes: 5

Jochen Ritzel
Jochen Ritzel

Reputation: 107786

def parts( s, sep ):
    while True:
        yield s
        try:
            # cut the string after the next sep
            s = s[s.index(sep)+1:]
        except ValueError:
            # no `sep` left
            break

print list(parts("a.b.c.d.e", '.'))
# ['a.b.c.d.e', 'b.c.d.e', 'c.d.e', 'd.e', 'e']

Upvotes: 2

Related Questions