Parentheses Balance Problem Solution in Python 3
This is a parentheses balance problem where the user will give the input as a string consisting of '(', ')', '[', ']', '{', and '}' symbols. We should check whether the expression consisting of all these symbols are balanced or not. If it is balanced the user should print 'Balanced' or else 'Unbalanced'. The user input ends at the end of the input file.
How did I Solve it?
Firstly, I stored all the possible opening symbols in one string and all the closing symbols in another string. Then I iterate through every symbol which user has given as a string. If opening symbols are found it is stored in a list. If closing symbols are found then it is compared with the symbols at the last index of the stored list. If its closing is found then we remove the opening symbols from the stored list or else the sequence of symbols is not balanced.
At last, if the stored list is empty then the sequence of symbols is balanced. If it is not empty then the sequence of symbols is not balanced. The source code for the parentheses balance problem solution in python 3 is given below.
You can buy the books on algorithms given below from amazon to enrich your understanding of algorithms.