Created
February 5, 2018 23:49
-
-
Save rayansostenes/f325fbcc9e6509207c1245aa4158d185 to your computer and use it in GitHub Desktop.
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
| #!/usr/bin/env python3 | |
| """ | |
| Statement | |
| Given an expression string exp, write a program to examine whether | |
| the pairs and the orders of {,},(,),[,] are correct in exp. | |
| For example: | |
| The program should print True for exp = “[()]{}{[()()]()}” and False for exp = “[(])” | |
| """ | |
| OPENING_CHARS = ('{','[','(') | |
| CLOSING_CHARS = ('}', ']', ')') | |
| CHAR_MAP = dict(zip(CLOSING_CHARS, OPENING_CHARS)) | |
| def validate_string(string): | |
| """ | |
| >>> validate_string('[()]{}{[()()]()}') | |
| True | |
| >>> validate_string('[(])') | |
| False | |
| >>> validate_string('[(]') | |
| False | |
| >>> validate_string('{[(())]}{}{}[]{}[()]') | |
| True | |
| >>> validate_string('(10*7)+(10−6)') | |
| True | |
| """ | |
| stack = [] | |
| try: | |
| for char in string: | |
| if char in OPENING_CHARS: | |
| stack.append(char) | |
| elif char in CLOSING_CHARS and CHAR_MAP[char] != stack.pop(): | |
| return False | |
| except IndexError: | |
| return False | |
| return len(stack) == 0 | |
| def main(): | |
| import doctest | |
| doctest.testmod() | |
| if __name__ == '__main__': | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment