Issue
Suppose I have the following method:
def _build_hierarchy(*keys):
# ...
If I call _build_hierarchy('a', 'b', 'c', 'd')
, I expect to get the following sequence of str
:
[
'a',
'a:b',
'a:c',
'a:d',
'a:b:c',
'a:b:d',
'a:b:c:d'
]
Notice that hierarchy is based on the order on which I provided the arguments.
To be honest, I have no idea how to approach this.
Ideally, I would like a really simple and pythonic solution if there is such thing.
Note: Solution needs to be compatible Python 2.7
Solution
As for now, it is not clear by which general rule a:c:d
does not appear in your output. Until precisions are added, this answer assumes it was simply forgotten.
The desired output is close to being the powerset of your input. We only require that the first element be always present. Thus, we can adapt the powerset
function from itertools recipes.
from itertools import chain, combinations
def _build_hierarchy (head, *tail, sep=':'):
for el in chain.from_iterable(combinations(tail, r) for r in range(len(tail)+1)):
yield sep.join((head,) + el)
for s in _build_hierarchy('a', 'b', 'c', 'd'):
print (s)
Output
a
a:b
a:c
a:d
a:b:c
a:b:d
a:c:d
a:b:c:d
Answered By - Olivier Melançon
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.