June 2018 Update
This commit is contained in:
parent
ba8067c3b7
commit
22f33d4004
5278 changed files with 84726 additions and 14379 deletions
24
Task/Balanced-brackets/Python/balanced-brackets-2.py
Normal file
24
Task/Balanced-brackets/Python/balanced-brackets-2.py
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
>>> 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
|
||||
Loading…
Add table
Add a link
Reference in a new issue