Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.5 kB
3
Indexable
Never
def main():
#    levels = [1, 2, 3, 3, 2, 3, 1]
    levels = [{'id': '1', 'level': 1, 'children': []},
            {'id': '1.1', 'level': 2, 'children': []},
            {'id': '1.2', 'level': 2, 'children': []},
            {'id': '1.2.1', 'level': 3, 'children': []},
            {'id': '1.2.2', 'level': 3, 'children': []},
            {'id': '1.3', 'level': 2, 'children': []},
            {'id': '2', 'level': 1, 'children': []},
            {'id': '2.1', 'level': 2, 'children': []},
            {'id': '2.1.1', 'level': 3, 'children': []},
            {'id': '2.1.1.1', 'level': 4, 'children': []},
            {'id': '2.1.2', 'level': 3, 'children': []},
            {'id': '2.1.3', 'level': 3, 'children': []},
            {'id': '2.2', 'level': 2, 'children': []},
            {'id': '2.3', 'level': 2, 'children': []},
            {'id': '3', 'level': 1, 'children': []},
            {'id': '3.1', 'level': 2, 'children': []}]

    level_map = {}
    for level in levels:
        level_map[level['id']] = level

    root = {'id': 'root', 'level': 0, 'children': []} 
    level_map['root'] = root

    levels_to_parent = {1:'root'}

    for i in range(len(levels)):
        level_map[levels_to_parent[levels[i]['level']]]['children'].append(levels[i]['id'])
        if i+1 < len(levels):
            if levels[i+1]['level'] > levels[i]['level']:
                levels_to_parent[levels[i+1]['level']] = levels[i]['id']

    print(levels)

if __name__ == '__main__':
    main()