python - Index of matching bracket character within a lambda function? -
i'm more curious in dire need. possible pass lambda function 2 arguments s
, , i
. s
string in question , i
index of first bracket; , have return index of complimentary bracket?
i should note needs work brackets ()
, , not {}
or []
.
for example
>>> f( '(() foo ) bar' , 0) 8
f
defined lambda function
edit: i'm aware numerous methods exist finding matching bracket. i, however, curious if can simplified lambda expression.
i'm far lazy worry corner cases, using itertools.accumulate
it's relatively straightforward:
f = lambda s,i: next((i i,x in enumerate(accumulate ({'(': 1, ')': -1}.get(c,0) c in s[i:]), i) if not x), none) in [31]: s = '(() foo ) bar' in [32]: f(s, 0) out[32]: 8 in [33]: f(s, 1) out[33]: 2 in [34]: f(s, 2)
this works tracking height of string, counting ( +1 , ) -1:
in [36]: list(accumulate({'(': 1, ')': -1}.get(c,0) c in s)) out[36]: [1, 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0]
Comments
Post a Comment