Last active
June 5, 2023 22:15
-
-
Save mjmeilahn/c417ec0641bfd493c9a4551e3f22dcc5 to your computer and use it in GitHub Desktop.
Python: Valid String Closures.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Return TRUE or FALSE whether the string has valid closures. | |
A valid closure can be: () or ({}) or []({}). | |
An invalid closure interrupts open/close characters. | |
Each opener character must have a closer character. | |
Each closer character must have an opener character. | |
""" | |
patterns = { | |
'{': '}', | |
'[': ']', | |
'(': ')', | |
} | |
def validPattern(str): | |
invalid = False | |
lis = list(str) | |
openers = list(patterns.keys()) | |
closers = list(patterns.values()) | |
o = [] | |
c = [] | |
for i, char in enumerate(lis): | |
o.append(char) if char in openers else None | |
c.append(char) if char in closers else None | |
try: | |
prev = lis[i - 1] | |
ahead = lis[i + 1] | |
openIndex = openers.index(prev) if prev in openers else None | |
closeIndex = closers.index(ahead) if ahead in closers else None | |
if prev in openers and ahead in closers and openIndex == closeIndex: invalid = True | |
except IndexError: pass | |
except Exception as e: print(e) | |
if invalid: return False | |
return False if len(o) != len(c) else True | |
print(validPattern('{([])}')) # True | |
print(validPattern('[]{()}')) # True | |
print(validPattern('{()}[]')) # True | |
print(validPattern('[)]')) # False | |
print(validPattern('{[]}(')) # False | |
print(validPattern('}[]')) # False | |
print(validPattern('{[]')) # False | |
print(validPattern('{[(])]}')) # False | |
print(validPattern('[(])')) # False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment