Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Node:
- def __init__(self, data):
- self.data = data
- self.next = None
- class Stack:
- # Constructor
- def __init__(self):
- self.top = 0
- self.head = None
- # Adds element to the Stack
- def push(self, data):
- self.top += 1
- if self.head == None:
- self.head = Node(data)
- else:
- newNode = Node(data)
- newNode.next = self.head
- self.head = newNode
- # Removes element from the stack
- def pop(self):
- if self.head == None:
- return "Stack Empty!"
- else:
- self.top -= 1
- item = self.head.data
- self.head = self.head.next
- return item
- # Returns the peek element of the stack
- def peek(self):
- if self.head == None:
- return "Stack Empty!"
- else:
- item = self.head.data
- return item
- # Checks if the stack is empty or not
- def is_empty(self):
- if self.head == None:
- return True
- else:
- return False
- def size(self):
- return self.top
- class CheckBalancedBracket:
- def is_balanced(self, expression):
- print(expression)
- stack = Stack()
- indexes = Stack()
- dict = {')': '(', '}': '{', ']': '['}
- index = 0
- for c in expression:
- index += 1
- if c == ')' or c == '}' or c == ']':
- if dict[c] != stack.peek():
- print("This expression is NOT correct.")
- if indexes.peek() != "Stack Empty!":
- print(f"Error at character #{indexes.peek()}. '{stack.peek()}' - not closed.")
- else:
- print(f"Error at character #{index}. '{c}' - not opened.")
- return
- else:
- stack.pop()
- indexes.pop()
- elif c == '(' or c == '[' or c == '{':
- stack.push(c)
- indexes.push(index)
- if stack.is_empty():
- print("This expression is correct.")
- return
- else:
- while stack.size() > 1:
- stack.pop()
- indexes.pop()
- print("This expression is NOT correct.")
- print(f"Error at character #{indexes.peek()}. '{stack.peek()}' - not closed.")
- return
- arithmaticExpression = input("Enter the expression: ")
- ans = CheckBalancedBracket()
- ans.is_balanced(arithmaticExpression)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement