I’m super new to coding and solving an assignment. The problem at hand is to convert an input string of letters and square brackets into a list of letters and lists. For example:the string ‘[abc]’ should return [‘a’,‘b’,‘c’]. I have the code running for a few test cases but it fails for the following string: ‘[a[b[c]]]’ which should return [‘a’,[‘b’,[‘c’]]], but instead my code returns [ ‘a’, [ ‘b’, [ ‘c’ ] ], [ ‘c’ ] ]. Can someone please tell me what I’m missing in my logic. Please help.
Here’s my logic so far that I’ve been able to research.
def str2list(s):
out = []
for x in s.split('['):
if ']' in x[:-1]:
x1 = x.split(']')
x1 = [list(x1[0])]+list(x1[1])
elif x[-1:] == ']':
x1 = list(x.strip(']'))
else:
x1 = list(x)
out.extend(x1)
return out
>Solution :
For an arbitrary nests of brackets, it’s better to use a recursive function:
def str2list(s):
def inner(item):
while True:
next_item = next(item)
if next_item == '[':
yield [x for x in inner(item)]
elif next_item == ']':
return
else:
yield next_item
return list(next(inner(iter(s))))
str2list('[a[b[c]]]')
Output:
['a', ['b', ['c']]]