Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 12111

Function to search sequential values on a list

$
0
0

I have the following list:

list = [   [2, 'A', '1'],   [6, 'A', '2'],   [6, 'S', '3'],   [9, 'A', '4'],   [6, 'A', '5'],   [6, 'A', '6'],   [6, 'S', '7'],   [9, 'A', '8'],   [9, 'A', '9'],   [6, 'A', '10'],   [10, 'S', '11'],   [13, 'S', '12'],   [13, 'S', '13'],   [16, 'A', '14']]

The first position of list is the level, the second the type of node and the third is the value.

I need to concatenate all values that have a higher level than before (i-1). I can have multiple A and S in each level, but every time I find a S type I need to still search until I find a higher level of S or A type. My desired output:

['1.2', '1.3.4', '1.5', '1.6', '1.7.8', '1.7.9', '1.10.11.13.14']

I tried to achieve this output with the following code:

def concat_levels(levels):     result = []     stack = []     for level in levels:        num, typ, name = level        while stack and stack [-1][0] >= num:           stack.pop()        if typ == 'A':           stack.append((num,name))        elif typ == 'S':           if stack:              current_path = '.'.join([x[1] for x in stack])              result.append(current_path +'.'+ name)     return result

However, when I run my function I got the following output:

['1.3', '1.7', '1.10.11', '1.10.12', '1.10.13']

Apparently my function is appending only on type == 'S', but why?


Viewing all articles
Browse latest Browse all 12111

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>