forked from PriyankaKhire/ProgrammingPracticePython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBalenceParenthesis.py
More file actions
35 lines (32 loc) · 1016 Bytes
/
BalenceParenthesis.py
File metadata and controls
35 lines (32 loc) · 1016 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#Given expression containing parenthesis output an expression that contains balenced parenthesis
#example:
#")(" -> ""
#"((())" -> "(())"
#"()())()" -> "()()()" or "(())()"
class Approch1(object):
def __init__(self, string):
self.string = string
def replace(self, string, index):
return string[:index]+"0"+string[index+1:]
def check(self):
stack = []
for i in range(len(self.string)):
if(self.string[i] == "("):
stack.append(i)
else:
if(stack and self.string[stack[-1]] == "("):
stack.pop()
else:
stack.append(i)
for i in stack:
self.string = self.replace(self.string, i)
output = ""
for letter in self.string:
if letter == "(" or letter == ")":
output = output+letter
print output
#Main
o = Approch1(")(")
o.check()
o = Approch1("(()))")
o.check()