Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

trying to convert string of letters and square brackets into a list of letters and lists

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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']]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading