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
|
||||
25
Task/Balanced-brackets/Python/balanced-brackets-3.py
Normal file
25
Task/Balanced-brackets/Python/balanced-brackets-3.py
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
>>> 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
|
||||
Loading…
Add table
Add a link
Reference in a new issue