Skip to content

Commit 58047e8

Browse files
committed
Done Chapter 6 Creativity questions
1 parent 5e44bc6 commit 58047e8

File tree

9 files changed

+562
-137
lines changed

9 files changed

+562
-137
lines changed

.idea/workspace.xml

+224-137
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
class Empty(Exception):
2+
"""Error attempting to access an element from an empty container"""
3+
pass
4+
5+
class Full(Exception):
6+
"""Error attempting to push an element to a full container."""
7+
pass
8+
9+
class ArrayStack:
10+
"""LIFO Stack implementation using a Python list as underlying storage."""
11+
12+
def __init__(self, maxlen = None):
13+
"""Create an empty stack."""
14+
self._data = []
15+
self._maxlen = maxlen
16+
17+
def __len__(self):
18+
"""Return the number of elements in the stack."""
19+
return len(self._data)
20+
21+
def is_empty(self):
22+
"""Return True if stack is empty."""
23+
return len(self._data) == 0
24+
25+
def push(self, e):
26+
"""Add element e to the top of the stack."""
27+
if self._maxlen is not None and (self._maxlen == len(self._data)):
28+
raise Full('Stack is full')
29+
self._data.append(e)
30+
31+
def top(self):
32+
"""Return the element at the top of the stack.
33+
34+
Raise empty exception if the stack is empty.
35+
"""
36+
if self.is_empty():
37+
raise Empty('Stack is empty.')
38+
return self._data[-1]
39+
40+
def pop(self):
41+
"""Remove and return the element from the top of the Stack.
42+
43+
Raise empty exception if the stack is empty.
44+
"""
45+
if self.is_empty():
46+
raise Empty('Stack is empty.')
47+
return self._data.pop()
48+
49+
def __str__(self):
50+
"""Prints the elements of stack"""
51+
result = ''.join(str(self._data[i]) + " " for i in range(len(self._data)))
52+
return result
53+
54+
55+
# Testing
56+
if __name__ == "__main__":
57+
S = ArrayStack(3)
58+
S.push(5)
59+
S.push(3)
60+
print(len(S))
61+
print(S)
62+
S.push(7)
63+
print(len(S))
64+
print(S)
65+
S.push(9)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
class Empty(Exception):
2+
"""Error attempting to access an element from an empty container"""
3+
pass
4+
5+
class Full(Exception):
6+
"""Error attempting to push an element to a full container."""
7+
pass
8+
9+
class ArrayStack:
10+
"""LIFO Stack implementation using a Python list as underlying storage."""
11+
12+
def __init__(self, maxlen = None):
13+
"""Create an empty stack."""
14+
self._maxlen = maxlen
15+
if self._maxlen is not None:
16+
self._data = [None] * self._maxlen
17+
self._n = 0
18+
19+
def __len__(self):
20+
"""Return the number of elements in the stack."""
21+
return self._n
22+
23+
def is_empty(self):
24+
"""Return True if stack is empty."""
25+
return self._n == 0
26+
27+
def push(self, e):
28+
"""Add element e to the top of the stack."""
29+
if self._maxlen is not None and (self._maxlen == self._n):
30+
raise Full('Stack is full')
31+
if self._data[self._n] is None:
32+
self._data[self._n] = e
33+
self._n += 1
34+
35+
def top(self):
36+
"""Return the element at the top of the stack.
37+
38+
Raise empty exception if the stack is empty.
39+
"""
40+
if self.is_empty():
41+
raise Empty('Stack is empty.')
42+
return self._data[-1]
43+
44+
def pop(self):
45+
"""Remove and return the element from the top of the Stack.
46+
47+
Raise empty exception if the stack is empty.
48+
"""
49+
if self.is_empty():
50+
raise Empty('Stack is empty.')
51+
answer = self._data[self._n-1]
52+
self._data[self._n-1] = None
53+
self._n -= 1
54+
return answer
55+
56+
def __str__(self):
57+
"""Prints the elements of stack"""
58+
result = ''.join(str(self._data[i]) + " " for i in range(len(self._data)) if self._data[i] is not None)
59+
return result
60+
61+
62+
# Testing
63+
if __name__ == "__main__":
64+
S = ArrayStack(3)
65+
S.push(5)
66+
S.push(3)
67+
print(len(S))
68+
print(S)
69+
S.push(7)
70+
print(len(S))
71+
print(S)
72+
print(S.is_empty())
73+
print(S.pop())
74+
print(S.is_empty())
75+
print(S)
76+
S.push(9)
77+
print(S.top())
78+
print(S)
79+
print(len(S))
80+
print(S.pop())
81+
S.push(6)
82+
print(S)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import stackarray as Stack
2+
3+
def transfer(S, T):
4+
"""Transfer the contents of stack of S to stack T"""
5+
6+
while not S.is_empty():
7+
T.push(S.pop())
8+
9+
10+
# Testing
11+
if __name__ == "__main__":
12+
S = Stack.ArrayStack()
13+
T = Stack.ArrayStack()
14+
U = Stack.ArrayStack()
15+
16+
S.push(12)
17+
S.push(10)
18+
S.push(25)
19+
print('S initial : ',S)
20+
transfer(S,T)
21+
print(T)
22+
transfer(T,U)
23+
print(U)
24+
transfer(U,S)
25+
print('S after : ',S)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import stackarray as Stack
2+
3+
def is_matched_html(raw):
4+
"""Return True if all HTML tags are properly matched;False otherwise"""
5+
6+
S = Stack.ArrayStack()
7+
j = raw.find('<')
8+
while j != -1:
9+
k = raw.find('>', j+1)
10+
if k == -1: # invalid tag
11+
return False
12+
tag = raw[j+1 : k] # strip away the tag
13+
space = tag.find(' ')
14+
if space != -1:
15+
tag = tag[0: space]
16+
if not tag.startswith('/'): # opening tag
17+
S.push(tag)
18+
else:
19+
if S.is_empty():
20+
return False
21+
if tag[1:] != S.pop():
22+
return False
23+
j = raw.find('<', k+1)
24+
return S.is_empty()
25+
26+
# Testing
27+
if __name__ == "__main__":
28+
raw_html = open('/home/mayank/Desktop/Algorithms-in-Python/06-Stacks-Queues-Deques/Exercises/Creativity/sample.html')
29+
html_list = []
30+
for line in raw_html:
31+
html_list.append(line)
32+
html_str = ''.join(html_list)
33+
print(html_str)
34+
print(is_matched_html(html_str))
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import stackarray as Stack
2+
3+
def postfix(expr):
4+
"""Returns the postfix expression of the given infix expr"""
5+
6+
precedence = ['(',')','^','/','*','+','-']
7+
postfix_expr = []
8+
9+
stack = Stack.ArrayStack()
10+
11+
for char in expr:
12+
if char in precedence:
13+
if precedence.index(char) == 0: # opening paranthesis
14+
stack.push(char)
15+
elif precedence.index(char) == 1: # closing paranthesis
16+
while not stack.is_empty():
17+
res = stack.pop()
18+
if res == '(':
19+
break
20+
postfix_expr.append(res)
21+
else: # other operators
22+
if len(stack) > 0 and precedence.index(char) > precedence.index(stack.top()):
23+
24+
while len(stack) > 0 and precedence.index(char) > precedence.index(stack.top()):
25+
if stack.top() != '(':
26+
postfix_expr.append(stack.pop())
27+
else:
28+
break
29+
30+
stack.push(char)
31+
else:
32+
stack.push(char)
33+
else:
34+
postfix_expr.append(char)
35+
36+
while not stack.is_empty():
37+
postfix_expr.append(stack.pop())
38+
39+
return ''.join(postfix_expr)
40+
41+
# Testing
42+
if __name__ == "__main__":
43+
print(postfix('(A+B)*(C-D)/(E*F)'))
44+
print(postfix('(A/B^C-D)'))
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
<html>
2+
<head>
3+
<title>Title</title>
4+
</head>
5+
<body>
6+
<center>
7+
<h1 attr = "hello"> The Little Boat </h1>
8+
</center>
9+
<p style="color:red;"> The storm tossed the little
10+
boat like a cheap sneaker in an
11+
old washing machine. The three
12+
drunken fishermen were used to
13+
such treatment, of course, but
14+
not the tree salesman, who even as
15+
a stowaway now felt that he
16+
had overpaid for the voyage. </p>
17+
<ol>
18+
<li> Will the salesman die? </li>
19+
<li> What color is the boat? </li>
20+
<li> And what about Naomi? </li>
21+
</ol>
22+
</body>
23+
</html>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
class Empty(Exception):
2+
"""Error attempting to access an element from an empty container"""
3+
pass
4+
5+
class ArrayStack:
6+
"""LIFO Stack implementation using a Python list as underlying storage."""
7+
8+
def __init__(self):
9+
"""Create an empty stack."""
10+
self._data = []
11+
12+
def __len__(self):
13+
"""Return the number of elements in the stack."""
14+
return len(self._data)
15+
16+
def is_empty(self):
17+
"""Return True if stack is empty."""
18+
return len(self._data) == 0
19+
20+
def push(self,e):
21+
"""Add element e to the top of the stack."""
22+
self._data.append(e)
23+
24+
def top(self):
25+
"""Return the element at the top of the stack.
26+
27+
Raise empty exception if the stack is empty.
28+
"""
29+
if self.is_empty():
30+
raise Empty('Stack is empty.')
31+
return self._data[-1]
32+
33+
def pop(self):
34+
"""Remove and return the element from the top of the Stack.
35+
36+
Raise empty exception if the stack is empty.
37+
"""
38+
if self.is_empty():
39+
raise Empty('Stack is empty.')
40+
return self._data.pop()
41+
42+
def __str__(self):
43+
"""Prints the elements of stack"""
44+
result = ''.join(str(self._data[i]) + " " for i in range(len(self._data)))
45+
return result
46+
47+
48+
49+
# Testing
50+
if __name__ == "__main__":
51+
S = ArrayStack()
52+
S.push(5)
53+
S.push(3)
54+
print(len(S))
55+
print(S.pop())
56+
print(S.is_empty())
57+
print(S.pop())
58+
print(S.is_empty())
59+
S.push(7)
60+
S.push(9)
61+
print(S.top())
62+
S.push(4)
63+
print(len(S))
64+
print(S.pop())
65+
S.push(6)

0 commit comments

Comments
 (0)