-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDS_Stacks.py
113 lines (79 loc) · 3.07 KB
/
DS_Stacks.py
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
from collections import deque
###### DEQUE OBJECTS ######
class Stack_Deque:
def __init__(self):
self.stack = deque() # create a new deque() object upon class object creation
# Add items to stack
def push(self, data):
return self.stack.append(data)
# Retrieve last added item & remove from deque object
def pop(self):
return self.stack.pop()
# Retrieve last added item, but DO NOT remove from deque object
def peek(self):
return self.stack[-1]
# Check to see if deque object is empty; returns a boolean of True if it is empty
def is_empty(self):
return len(self.stack) == 0
# Returns the number of items in the deque object
def size(self):
return len(self.stack)
# What to print out when Stack_Deque object name is invoked
def __repr__(self):
if self.is_empty():
return "No items have been added to deque yet"
else:
items = []
reverse_index = self.size() - 1
max_index = self.size() - 1
while reverse_index >= 0:
# First item added
if reverse_index == 0:
items.append("[FIRST: %s]" % self.stack[reverse_index])
# Last item added
elif reverse_index == max_index:
items.append("[LAST: %s]" % self.stack[max_index])
# All the rest of the items
else:
items.append("[%s]" % self.stack[reverse_index])
reverse_index -= 1
return '\n'.join(items)
###### LIST OBJECTS ######
class Stack_List:
def __init__(self):
self.stack = [] # create a new list object upon class object creation
# Add items to stack
def push(self, data):
return self.stack.append(data)
# Retrieve last added item & remove from list
def pop(self):
return self.stack.pop()
# Retrieve last added item, but DO NOT remove from list
def peek(self):
return self.stack[-1]
# Check to see if list is empty; returns a boolean of True if it is empty
def is_empty(self):
return len(self.stack) == 0
# Returns the number of items in the list
def size(self):
return len(self.stack)
# What to print out when Stack_List object name is invoked
def __repr__(self):
if self.is_empty():
return "No items have been added to list yet"
else:
items = []
reverse_index = self.size() - 1
max_index = self.size() - 1
while reverse_index >= 0:
# First item added
if reverse_index == 0:
items.append("[FIRST: %s]" % self.stack[reverse_index])
# Last item added
elif reverse_index == max_index:
items.append("[LAST: %s]" % self.stack[max_index])
# All the rest of the items
else:
items.append("[%s]" % self.stack[reverse_index])
reverse_index -= 1
return '\n'.join(items)