Created
June 26, 2022 18:22
-
-
Save dusekdan/ecfbd464a661ed611fdd458348280f82 to your computer and use it in GitHub Desktop.
Implement a function that validates whether given bracket-string (both single-type and multiple-type) is valid.
This file contains hidden or 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
"""Implement function(s) to validate whether specified bracket string is valid. | |
For a string to be valid, it has to have the same amount of the brackets of the | |
same type (naive, simple implementation) and these bracket types cannot cross | |
(complex string/implementation) - just like they couldn't in a math. equation. | |
Solution to this exercise typically uses stack and pushes symbols onto it as | |
they are read, and pops them from its top as their counter parts are read. | |
""" | |
def main(): | |
# Valid and invalid samples for single and multiple bracket type | |
valid_simple = "(())" | |
invalid_simple = "(((()))" | |
valid_complex = "{<[()()]>([[]]<>)}" | |
invalid_complex = "{<[(])([)]>([[]]<>)}" | |
print(f"String: {valid_simple} is valid={validate_naive_stack_implementation(valid_simple)}") | |
print(f"String: {invalid_simple} is valid={validate_naive_stack_implementation(invalid_simple)}") | |
print(f"String: {valid_complex} is valid={validate_complex_parenthesis_string(valid_complex)}") | |
print(f"String: {invalid_complex} is valid={validate_complex_parenthesis_string(invalid_complex)}") | |
def validate_naive_stack_implementation(input): | |
"""Validates strings that use only one type of brackets.""" | |
pseudo_stack = [] | |
for character in input: | |
if character == '(': | |
pseudo_stack.append(character) | |
if character == ')': | |
pseudo_stack.pop() | |
return len(pseudo_stack) == 0 | |
def validate_complex_parenthesis_string(input): | |
pseudo_stack = [] | |
for char in input: | |
if _is_opening_bracket(char): | |
pseudo_stack.append(_get_closing_bracket_for(char)) | |
else: # Assumption: Entering this branch means closing bracket is read | |
if len(pseudo_stack) == 0: | |
return False | |
last_expression_bracket = pseudo_stack.pop() | |
if(char != last_expression_bracket): | |
return False | |
print(pseudo_stack) | |
return len(pseudo_stack) == 0 | |
def _is_opening_bracket(bracket): | |
return bracket in ['(', '<', '{', '['] | |
def _get_closing_bracket_for(bracket): | |
bracket_mapping = {'(': ')', '<': '>', '{':'}', '[':']'} | |
return bracket_mapping[bracket] | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment