Skip to content

Commit 415acbc

Browse files
committed
Learnt Stack from the book.
1 parent 3129f6d commit 415acbc

File tree

8 files changed

+318
-332
lines changed

8 files changed

+318
-332
lines changed

.idea/workspace.xml

+160-332
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Binary file not shown.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import stackarray as Stack
2+
3+
def is_matched(expr):
4+
"""Returns True if all the delimiters are matched properly;False otherwise."""
5+
S = Stack.ArrayStack()
6+
left = '({['
7+
right = ')}]'
8+
for c in expr:
9+
if c in left:
10+
S.push(c)
11+
elif c in right:
12+
if S.is_empty():
13+
return False
14+
if right.index(c) != left.index(S.pop()):
15+
return False
16+
return S.is_empty()
17+
18+
# Testing
19+
if __name__ == "__main__":
20+
print(is_matched('[(5+x)-(6-y)]'))
21+
print(is_matched('{2*3+(x - 7 + [14-17])}'))
22+
print(is_matched('(23(12)]'))
23+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
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+
if not tag.startswith('/'): # opening tag
14+
S.push(tag)
15+
else:
16+
if S.is_empty():
17+
return False
18+
if tag[1:] != S.pop():
19+
return False
20+
j = raw.find('<', k+1)
21+
return S.is_empty()
22+
23+
# Testing
24+
if __name__ == "__main__":
25+
raw_html = open('/home/mayank/Desktop/Algorithms-in-Python/06-Stacks-Queues-Deques/Stacks/sample.html')
26+
html_list = []
27+
for line in raw_html:
28+
html_list.append(line)
29+
html_str = ''.join(html_list)
30+
print(html_str)
31+
print(is_matched_html(html_str))
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import stackarray as Stack
2+
3+
def reverse_file(filename):
4+
"""Overwrite a a given file with its contents line-by-line reversed."""
5+
S = Stack.ArrayStack()
6+
original = open(filename)
7+
for line in original:
8+
S.push(line.rstrip('\n'))
9+
original.close()
10+
11+
# Now we overwrite the file
12+
output = open(filename,'w')
13+
while not S.is_empty():
14+
output.write(S.pop() + '\n')
15+
output.close()
16+
17+
18+
# Testing
19+
if __name__ == "__main__":
20+
reverse_file('/home/mayank/Desktop/Algorithms-in-Python/06-Stacks-Queues-Deques/Stacks/sample.txt')
+23
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> The Little Boat </h1>
8+
</center>
9+
<p> 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,2 @@
1+
Let's see whether it works or not.
2+
Trying out reverse the contents of file using stack.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
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+
43+
# Testing
44+
if __name__ == "__main__":
45+
S = ArrayStack()
46+
S.push(5)
47+
S.push(3)
48+
print(len(S))
49+
print(S.pop())
50+
print(S.is_empty())
51+
print(S.pop())
52+
print(S.is_empty())
53+
S.push(7)
54+
S.push(9)
55+
print(S.top())
56+
S.push(4)
57+
print(len(S))
58+
print(S.pop())
59+
S.push(6)

0 commit comments

Comments
 (0)