Search code examples
pythonrecursionnested

how to recursively create nested list from string input


So, I would like to convert my string input

'f(g,h(a,b),a,b(g,h))' 

into the following list

['f',['g','h',['a','b'],'a','b',['g','h']]]

Essentially, I would like to replace all '(' into [ and all ')' into ].

I have unsuccessfully tried to do this recursively. I thought I would iterate through all the variables through my word and then when I hit a '(' I would create a new list and start extending the values into that newest list. If I hit a ')', I would stop extending the values into the newest list and append the newest list to the closest outer list. But I am very new to recursion, so I am struggling to think of how to do it

word='f(a,f(a))'
empty=[]
def newlist(word):
    listy=[]
    for i, letter in enumerate(word):
        if letter=='(':
            return newlist([word[i+1:]])
        if letter==')':
            listy.append(newlist)
        else:
            listy.extend(letter)
        
    return empty.append(listy)

 

Solution

  • Quite an interesting question, and one I originally misinterpreted. But now this solution works accordingly. Note that I have used list concatenation + operator for this solution (which you usually want to avoid) so feel free to improve upon it however you see fit.

    Good luck, and I hope this helps!

    # set some global values, I prefer to keep it
    # as a set incase you need to add functionality
    # eg if you also want {{a},b} or [ab<c>ed] to work
    OPEN_PARENTHESIS = set(["("])
    CLOSE_PARENTHESIS = set([")"])
    SPACER = set([","])
    
    def recursive_solution(input_str, index):
    
        # base case A: when index exceeds or equals len(input_str)
        if index >= len(input_str):
            return [], index
        
        char = input_str[index]
    
        # base case B: when we reach a closed parenthesis stop this level of recursive depth
        if char in CLOSE_PARENTHESIS:
            return [], index
    
        # do the next recursion, return it's value and the index it stops at
        recur_val, recur_stop_i = recursive_solution(input_str, index + 1)
    
        # with an open parenthesis, we want to continue the recursion after it's associated
        # closed parenthesis. and also the recur_val should be within a new dimension of the list
        if char in OPEN_PARENTHESIS:
            continued_recur_val, continued_recur_stop_i = recursive_solution(input_str, recur_stop_i + 1)
            return [recur_val] + continued_recur_val, continued_recur_stop_i
        
        # for spacers eg "," we just ignore it
        if char in SPACER:
            return recur_val, recur_stop_i
        
        # and finally with normal characters, we just extent it 
        return [char] + recur_val, recur_stop_i