1

I want to be able to turn the strings for example: '(* (+ int (+ int real)) int)'
into a nested list where the brackets are start/end of lists, looking like this(in this case)

['*', ['+', 'int', ['+', 'int', 'real']], 'int']

I have tried with the following code but it doesn't work

def bracketCheck(el):
if el == ')' or el == '(':
    return False
else:
    return True



def stringIntoList(lst):
lst1 = ''
lst2 = []

for i in range(0, len(lst)-1):
    if bracketCheck(lst[i]):
        lst1 += lst[i]
    elif lst[i] == '(':
        b = stringIntoList(lst[i:])
    elif lst[i] == ')':
        lst2.append(lst1)
        lst2.append(b)
        lst1 = ''
return lst2 
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • Not downvoting, but question could be improved by addressing some elements of this (http://idownvotedbecau.se/itsnotworking/) common problem. – lampShadesDrifter Nov 21 '18 at 19:24

1 Answers1

0

You can make the function keep track of the lengths of the substrings that the recursive calls consume:

def stringIntoList(string):
    output = []
    token = ''
    index = 0
    while index < len(string):
        char = string[index]
        index += 1
        if char in '() ' and token:
            output.append(token)
            token = ''
        if char == '(':
            lst, offset = stringIntoList(string[index:])
            output.append(lst)
            index += offset
        elif char == ')':
            break
        elif char != ' ':
            token += char
    return output, index

so that:

stringIntoList('(* (+ int (+ int real)) int)')[0][0]

returns:

['*', ['+', 'int', ['+', 'int', 'real']], 'int']

Note that the first [0] is to obtain the list since the second item is the offset, while the second [0] is to obtain the first sublist of the list, since you apparently assume that your input always starts and ends with parentheses.

blhsing
  • 91,368
  • 6
  • 71
  • 106