You are looping over a string (s
, with value '[p[da]]'
), so samp
will be each character in the string in turn ('['
, 'p'
, etc.) - you then proceed to strip off brackets, and turn the result into a list of characters. That list will always be either empty if the character was a bracket, or the character if it was not. Your code does nothing to group nested brackets, or anything of the sort.
A non-recursive solution:
def makelist(s):
part = []
stack = []
for ch in s:
if ch == '[':
part.append([])
stack.append(part)
part = part[-1]
elif ch == ']':
if stack:
part = stack.pop()
else:
raise SyntaxError('Too many closing brackets')
else:
part.append(ch)
if stack:
raise SyntaxError('Too many opening brackets')
return part
print(makelist('[p[da]]'))
print(makelist('[a[b[c]d]e]'))
print(makelist('123'))
try:
print(makelist('[a]]'))
except Exception as e:
print(e)
try:
print(makelist('[[a]'))
except Exception as e:
print(e)
Result:
[['p', ['d', 'a']]]
[['a', ['b', ['c'], 'd'], 'e']]
['1', '2', '3']
Too many closing brackets
Too many opening brackets