Skip to content

Commit 13f0d8f

Browse files
committed
answers for stack practice probs
1 parent be48148 commit 13f0d8f

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

data_structures/5_Stack/stack.py

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,24 @@
66
77
reverse_string("We will conquere COVID-19") should return "91-DIVOC ereuqnoc lliw eW"
88
'''
9+
from collections import deque
10+
11+
12+
def reverse_string(str):
13+
reversed = ""
14+
stack = deque()
15+
stack.extend(str)
16+
l = len(stack)
17+
while l != 0:
18+
reversed += stack.pop()
19+
l -= 1
20+
return reversed
21+
22+
23+
r1 = reverse_string("hello")
24+
print(f"reverse string of hello: {r1}")
25+
r2 = reverse_string("We will conquere COVID-19")
26+
print(f"reverse string of We will conquere COVID-19: {r2}")
927

1028
'''
1129
2. Write a function in python that checks if paranthesis in the string are balanced or not.
@@ -19,3 +37,44 @@
1937
is_balanced("[a+b]*(x+2y)*{gg+kk}") --> True
2038
2139
'''
40+
41+
42+
def is_match(chr):
43+
dict = {'}': '{', ']': '[', ')': '('}
44+
return dict[chr]
45+
46+
47+
def is_balanced(str):
48+
stack = deque()
49+
for chr in str:
50+
if chr in "{([":
51+
stack.append(chr)
52+
if chr in "})]":
53+
if len(stack) == 0 or is_match(chr) != stack.pop():
54+
return False
55+
return len(stack) == 0
56+
"""
57+
# first solution I wrote has a problem
58+
# it doesn't consider when it has equal number of parenthese each side but not the wrong one
59+
# {[}] --> gives me True, which is False indeed
60+
stack = deque()
61+
for chr in str:
62+
if chr in "{([":
63+
stack.append(chr)
64+
if chr in "})]":
65+
try:
66+
stack.pop()
67+
except IndexError:
68+
return False
69+
return len(stack) == 0
70+
"""
71+
72+
73+
print("is_balanced(\"({a+b}))\"): " + str(is_balanced("({a+b})")))
74+
print("is_balanced(\"))((a+b}{\"): " + str(is_balanced("))((a+b}{")))
75+
print("is_balanced(\"((a+b))\"): " + str(is_balanced("((a+b))")))
76+
print("is_balanced(\"))\"): " + str(is_balanced("))")))
77+
print("is_balanced(\"[a+b]*(x+2y)*{gg+kk}\") : " +
78+
str(is_balanced("[a+b]*(x+2y)*{gg+kk}")))
79+
80+
print("is_balanced(\"({a+b)})\"): " + str(is_balanced("({a+b)}")))

0 commit comments

Comments
 (0)