I want a Python function that takes a string and returns an array where each item in the array is a character, or another such array. Nested array with '(' and in '') marking the beginning of the input string.
Thus, the function is as follows:
1) foo("abc") == ["a", "b", "c"] 2) foo("a(b)c") == ["a", ["b"], "c"] 3) foo("a(b(c))") == ["a", ["b", ["c"]]] 4) foo("a(b(c)") == error: closing bracket is missing 5) foo("a(b))c") == error: opening bracket is missing 6) foo("a)b(c") == error: opening bracket is missing
Note: I prefer solutions purely functional.
solution
def foo(s): def foo_helper(level=0): try: token = next(tokens) except StopIteration: if level != 0: raise Exception('missing closing paren') else: return [] if token == ')': if level == 0: raise Exception('missing opening paren') else: return [] elif token == '(': return [foo_helper(level+1)] + foo_helper(level) else: return [token] + foo_helper(level) tokens = iter(s) return foo_helper()
with,
>>> foo('a((b(c))d)(e)') ['a', [['b', ['c']], 'd'], ['e']]
This article first appeared in Python black hole net , blog updated simultaneously Park