File tree Expand file tree Collapse file tree 1 file changed +59
-0
lines changed Expand file tree Collapse file tree 1 file changed +59
-0
lines changed Original file line number Diff line number Diff line change 6
6
7
7
reverse_string("We will conquere COVID-19") should return "91-DIVOC ereuqnoc lliw eW"
8
8
'''
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 } " )
9
27
10
28
'''
11
29
2. Write a function in python that checks if paranthesis in the string are balanced or not.
19
37
is_balanced("[a+b]*(x+2y)*{gg+kk}") --> True
20
38
21
39
'''
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)}" )))
You can’t perform that action at this time.
0 commit comments