Balanced brackets: Difference between revisions

→‎{{header|Python}}: itertools and numpy implementations
(→‎{{header|Python}}: itertools and numpy implementations)
Line 4,628:
 
=={{header|Python}}==
===Procedural===
<lang python>>>> def gen(N):
... txt = ['[', ']'] * N
Line 4,655 ⟶ 4,656:
'[[[[]][]]][[][]]' is balanced
'][[][[]]][]]][[[[]' is not balanced</lang>
 
=== Functional ===
{{works with|Python|3.2}}
Rather than explicitly track the count, we can just write the per-element test and use stdlib functions to turn it into a whole-sequence test. It's straightforwardly declarative, and hard to get wrong, but whether it's actually easier to understand depends on how familiar the reader is with thinking in `itertools` style.
 
<lang python>>>> from itertools import accumulate
>>> from random import shuffle
>>> def gen(n):
... txt = list('[]' * n)
... shuffle(txt)
... return ''.join(txt)
...
>>> def balanced(txt):
... brackets = ({'[': 1, ']': -1}.get(ch, 0) for ch in txt)
... return all(x>=0 for x in accumulate(brackets))
...
>>> for txt in (gen(N) for N in range(10)):
... print ("%-22r is%s balanced" % (txt, '' if balanced(txt) else ' not'))
...
'' is balanced
'][' is not balanced
'[]][' is not balanced
']][[[]' is not balanced
'][[][][]' is not balanced
'[[[][][]]]' is balanced
'][[[][][]][]' is not balanced
'][]][][[]][[][' is not balanced
'][[]]][][[]][[[]' is not balanced
'][[][[]]]][[[]][][' is not balanced</lang>
 
=== Array Programming ===
{{libheader| numpy}}
The numpy library gives us a way to write just the elementwise tests and automatically turn them into whole-sequence tests, although it can be a bit clumsy to use for character rather than numeric operations. The simplicity of the final expression probably doesn't make up for all that extra clumsiness in this case.
 
<lang python>>>> import numpy as np
>>> from random import shuffle
>>> def gen(n):
... txt = list('[]' * n)
... shuffle(txt)
... return ''.join(txt)
...
>>> m = np.array([{'[': 1, ']': -1}.get(chr(c), 0) for c in range(128)])
>>> def balanced(txt):
... a = np.array(txt, 'c').view(np.uint8)
... return np.all(m[a].cumsum() >= 0)
...
>>> for txt in (gen(N) for N in range(10)):
... print ("%-22r is%s balanced" % (txt, '' if balanced(txt) else ' not'))
...
'' is balanced
'][' is not balanced
'[[]]' is balanced
'[]][][' is not balanced
']][]][[[' is not balanced
'[[]][[][]]' is balanced
'[][[]][[]]][' is not balanced
'[][[[]][[]]][]' is balanced
'[[][][[]]][[[]]]' is balanced
'][]][][[]][]][][[[' is not balanced</lang>
 
=={{header|Qi}}==
Anonymous user