开发者

Transforming level depth to subordinate count

开发者 https://www.devze.com 2023-02-10 12:17 出处:网络
Let\'s consider this sample example text file: Level: 1 Level: 1 Level: 2 Level: 2 Level: 2 Level: 3 Level: 3

Let's consider this sample example text file:

Level: 1
Level: 1
Level: 2
Level: 2
Level: 2
Level: 3
Level: 3
Level: 1
Level: 2
Level: 2
Level: 1

I need to transform those lines using provided level data to subordinate count (excluding subordinates of subordinates) The result should look like this:

:0
:3
:0
:0
:2
:0
:0
:2
:0
:0
:0

My first thought was transforming text file to XML and use simple xml parser technique as solution, but then I remembered that python sometimes can do magic things and thought to ask fo开发者_如何学JAVAr advice if someone knows how to do this in "pythonic" way (without xml help)

Thanks


A possible solution:

input_text = """Level: 1
Level: 1
Level: 2
Level: 2
Level: 2
Level: 3
Level: 3
Level: 1
Level: 2
Level: 2
Level: 1"""

# Parse input text into a list of levels (as int)
levels = []
for line in input_text.split('\n'):
    try:
        levels.append(int(line.split(': ', 1)[-1]))
    except Exception:
        pass # skip line

# Compute how many children each node has by counting the number of
# consecutive subsequent lines that belong to exactly the next level
counters = [0] * len(levels)
for i, level in enumerate(levels):
    for other in levels[i + 1:]:
        if other == level + 1:
            counters[i] += 1
        elif other == level:
            break

print '\n'.join(':%d' % c for c in counters)
0

精彩评论

暂无评论...
验证码 换一张
取 消