Created
May 4, 2021 18:07
-
-
Save josephphyo/1f4ce0f738eacce7bab4d3b94001827d to your computer and use it in GitHub Desktop.
Stack Exercise - Python
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
## (5+6)*(7+8)/(4+3) #Checking Bracket with Stack | |
## from stack (FileName) (stack.py) import Stack (class) | |
from stack import Stack | |
def perChecker(symbolString): | |
s = Stack() | |
balanced = True | |
index = 0 | |
while index < len(symbolString) and balanced: | |
symbol = symbolString[index] | |
if symbol == "(": | |
s.push(symbol) | |
else: | |
if s.is_empty(): | |
balanced = False | |
else: | |
s.pop() | |
index = index + 1 | |
if balanced and s.is_empty(): | |
return True | |
else: | |
return False | |
print(perChecker('(())')) | |
print(perChecker('(')) |
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
class Stack: | |
def __init__(self): | |
self.items = [] # Empty Array | |
def is_empty(self): | |
return self.items == [] # Check Stack is Empty or Not | |
def push(self,item): | |
self.items.append(item) | |
def pop(self): | |
return self.items.pop() | |
def peek(self): | |
return self.items[len(self.items) - 1 ] | |
def size(self): | |
return len(self.items) | |
s = Stack() # creating object of the class | |
print(s.is_empty()) | |
s.push(4) | |
s.push("dog") | |
print(s.peek()) | |
s.push("duck") | |
print(s.size()) | |
s.push("cat") | |
print(s.pop()) #cat | |
print(s.pop()) #true | |
print(s.size()) | |
print("=======") | |
s2 = Stack() | |
s.push("tiger") | |
print(s.peek()) | |
print(s.size()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment