Home > Software design >  Converting string to list - str2list(‘[abc]’) should return [‘a’,‘b’,‘c’]
Converting string to list - str2list(‘[abc]’) should return [‘a’,‘b’,‘c’]

Time:12-07

I'm new to programming and I'm trying to convert an input string of letters and square brackets (i.e., [ and ]) into a list of letters and lists. The square brackets identify where a list starts and ends, while each letter translates into an element of the corresponding list.

str2list(‘[abc]’) should return [‘a’,‘b’,‘c’] str2list(‘[a[bc]]’) should return [‘a’,[‘b’,‘c’]]

My attempts at it are:

Attempt 1:

  def str2list(s):
      list1=[]
      list1[:0]=s
    #     s.replace(',', '')
    #     a = s.split(",")
      list1.append([])
      return list1

 str2list('[abc]')

Attempt 2:

def str2list(s):
    list1=[]
    list1[:0]=s
    return list1

str2list('[abc]')

But, I'm not getting the desired output. I'm stuck. Could someone please help me and tell me what needs to be done?

CodePudding user response:

def s2l(i):
    while True:
        n = i.next()
        #print 'n =', n
        if n == '[':
            yield [x for x in s2l(i) ]
        elif n == ']':
            return
        else:
            yield n

res = s2l(iter("[ab[123]cd]")).next()

CodePudding user response:

You just have to think carefully about if-else-conditions:

def str2list(my_str):
    out = []
    for s in my_str.split('['):
        if ']' in s[:-1]:
            s1 = s.split(']')
            s1 = [list(s1[0])] list(s1[1])
        elif s[-1:] == ']':
            s1 = [list(s.strip(']'))]
        else:
            s1 = list(s)
        out.extend(s1)
    return out

print(str2list('[wewr[sfs]]'))
print(str2list('[wewr[sfs]da]'))
print(str2list('[wewr[sfs]da[ds]]'))
print(str2list('[wewr[sfs]da[ds][dfd]]'))

Output:

['w', 'e', 'w', 'r', ['s', 'f', 's']]
['w', 'e', 'w', 'r', ['s', 'f', 's'], 'd', 'a']
['w', 'e', 'w', 'r', ['s', 'f', 's'], 'd', 'a', ['d', 's']]
['w', 'e', 'w', 'r', ['s', 'f', 's'], 'd', 'a', ['d', 's'], ['d', 'f', 'd']]
  • Related