Skip to content

Commit 751d1c9

Browse files
author
Sagar Paul
committed
_--_
1 parent 87b2291 commit 751d1c9

2 files changed

+104
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
'''
2+
Write a function in python that can reverse a string using stack data structure.
3+
4+
reverse_string("We will conquere COVID-19") should return "91-DIVOC ereuqnoc lliw eW"
5+
6+
'''
7+
8+
from collections import deque
9+
10+
class Stack:
11+
def init(self):
12+
self.container = deque()
13+
14+
def push(self, val):
15+
self.container.append(val)
16+
17+
def pop(self):
18+
return self.container.pop()
19+
20+
def peek(self):
21+
return self.container[-1]
22+
23+
def is_empty(self):
24+
return len(self.container) == 0
25+
26+
def size(self):
27+
return len(self.container)
28+
29+
def reverse_string(s):
30+
stack = Stack()
31+
32+
for ch in s:
33+
stack.push(ch)
34+
35+
rstr = ''
36+
while stack.size()!=0:
37+
rstr += stack.pop()
38+
39+
return rstr
40+
41+
if name == 'main':
42+
print(reverse_string("We will conquere COVI-19"))
43+
print(reverse_string("I am the king"))
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
'''
2+
Write a function in python that checks if paranthesis in the string are balanced or not. Possible parantheses are "{}',"()" or "[]".
3+
4+
exmple:
5+
6+
is_balanced("({a+b})") --> True
7+
is_balanced("))((a+b}{") --> False
8+
is_balanced("((a+b))") --> True
9+
is_balanced("))") --> False
10+
is_balanced("[a+b](x+2y){gg+kk}") --> True
11+
12+
'''
13+
from collections import deque
14+
15+
class Stack:
16+
def init(self):
17+
self.container = deque()
18+
19+
def push(self, val):
20+
self.container.append(val)
21+
22+
def pop(self):
23+
return self.container.pop()
24+
25+
def peek(self):
26+
return self.container[-1]
27+
28+
def is_empty(self):
29+
return len(self.container) == 0
30+
31+
def size(self):
32+
return len(self.container)
33+
34+
def is_match(ch1, ch2):
35+
match_dict = {
36+
')': '(',
37+
']': '[',
38+
'}': '{'
39+
}
40+
return match_dict[ch1] == ch2
41+
42+
def is_balanced(s):
43+
stack = Stack()
44+
for ch in s:
45+
if ch=='(' or ch=='{' or ch == '[':
46+
stack.push(ch)
47+
if ch==')' or ch=='}' or ch == ']':
48+
if stack.size()==0:
49+
return False
50+
if not is_match(ch,stack.pop()):
51+
return False
52+
53+
return stack.size()==0
54+
55+
if name == 'main':
56+
print(is_balanced("({a+b})"))
57+
print(is_balanced("))((a+b}{"))
58+
print(is_balanced("((a+b))"))
59+
print(is_balanced("((a+g))"))
60+
print(is_balanced("))"))
61+
print(is_balanced("[a+b](x+2y){gg+kk}"))

0 commit comments

Comments
 (0)