-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathAdvanced_DLL.py
275 lines (216 loc) · 9.2 KB
/
Advanced_DLL.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
# Copied from internet, Author name is below:
__author__ = "Adam Traub"
__date__="2/16/2011"
class LinkedList:
'''Linked List'''
class __Node:
'''
private node object. Node's consist of an element
and a pointer to the previous and next Node'''
def __init__(self, element=None):
self.__element = element
self.__next = None
self.__previous = None
self.__toMove = (self.getPrevious,self.getNext)
def __str__(self):
'''string representation of Node'''
return str(self.__element)
def hasNext(self):
'''returns true if the Node has a next Node'''
return self.__next != None
def getNext(self):
'''get next Node'''
return self.__next
def setNext(self,nextItem):
'''set the next Node of the Node'''
self.__next = nextItem
def hasPrevious(self):
'''returns true if the Node has a previous Node'''
return self.__previous != None
def getPrevious(self):
'''get previous Node'''
return self.__previous
def setPrevious(self,previousItem):
'''set the previous Node of the Node'''
self.__previous = previousItem
def getPreviousAndNext(self):
'''gets previous and next Nodes'''
return self.__previous,self.__next
def setPreviousAndNext(self, previousItem, nextItem):
'''set the previous and Next Node of the Node'''
self.__previous = previousItem
self.__next = nextItem
def getElement(self):
'''get the element of the Node'''
return self.__element
def setElement(self, element):
'''set the element of the current Node'''
self.__element = element
def get(self,gettingNextElement):
'''Get element based on a boolean. True for next. False for previous'''
return self.__toMove[int(gettingNextElement)]()
def __init__(self):
'''Creates the LinkedList'''
self.__first = LinkedList.__Node()
self.__last = self.__first
self.__length = 0
def __len__(self):
'''returns the length of the list O(1)'''
return self.__length
def count(self):
'''returns the length of the list O(1)'''
return self.__length
def isEmpty(self):
'''returns true if the list is empty'''
return self.__length == 0
def append(self, element):
'''Add element to last position of the list'''
self.__handleLinking(LinkedList.__Node(element),self.__last,None,False)
def pop(self, index =None):
'''Removes and returns an element in the list. last element by default.'''
if self.__length == 0:
raise IndexError("pop from empty list")
#utilize default parameter
if index ==None:
index = self.__length-1
toRemove = self.__getNodeAtPosition(self.__checkIndex(index))
self.__handleLinking(toRemove,toRemove.getPrevious(),toRemove.getNext(),True)
return toRemove.getElement()
def insert(self, index, element):
'''inserts an element to the given index'''
toMove = self.__getNodeAtPosition(self.__checkIndex(index))
self.__handleLinking(LinkedList.__Node(element),toMove.getPrevious(),toMove,False)
def extend(self, toAdd):
'''extend current list by adding an iterable structure to the end'''
for value in toAdd:
self.append(value)
def index(self, x):
'''Find index of first ocurrence of a given value'''
for dex,value in enumerate(self):
if x == value:
return dex
raise ValueError("LinkedList.index(x): x not in list")
def reverse(self):
'''reverse the linked list'''
for index in range(self.__length-1,-1,-1):
self.append(self.pop(index))
def __getitem__(self, index):
'''Allows for indexing, index must be an integer'''
#accounts for slicing
if type(index) == slice:
return self.__sliceList(index)
return self.__getNodeAtPosition(self.__checkIndex(index)).getElement()
def __add__(self, other):
'''adds a an iterable data structure to the linked list'''
retList = LinkedList()
for item in self:
retList.append(item)
for item in other:
retList.append(item)
return retList
def __setitem__(self, index, element):
'''Sets the item at a given index to a new element.'''
self.__getNodeAtPosition(self.__checkIndex(index)).setElement(element)
def __str__(self):
'''returns a string representation of the list'''
if self.__length == 0:
return '[]'
retString = "["
currentElement = self.__first.getNext()
for i in range(self.__length):
retString += str(currentElement) +", "
currentElement = currentElement.getNext()
return retString[:-2] + ']'
#Private functions
def __handleLinking(self, center, previous, nextNode, isRemoving):
'''takes care of linking Nodes on inserts and removals'''
def updateLinks(center, previous, nextNode, newNext, newLast, newPrevious, toAdd):
'''A nested function to reduce repeated code in setting links'''
if previous != None:
previous.setNext(newNext)
if nextNode == None:
self.__last = newLast
else:
nextNode.setPrevious(newPrevious)
self.__length += toAdd
if isRemoving:
updateLinks(center, previous, nextNode, nextNode, previous, previous, -1)
else:
center.setPreviousAndNext(previous,nextNode)
updateLinks(center, previous, nextNode, center, center, center, 1)
def __sliceList(self,theSlice):
'''(Private) function to handle slicing. Returns a Linked List'''
def determineStartStopStep(valToCheck, step, positiveStep, negativeStep):
'''nested function to reduce repeated code in determining slicing handling'''
if valToCheck == None:
if step > 0:
return positiveStep
else:
return negativeStep
else:
return valToCheck
retList = LinkedList()
#Following conditions handles the x[start:stop:step] notation
step = determineStartStopStep(theSlice.step,1,1,1)
start = determineStartStopStep(theSlice.start,step,0,self.__length-1)
stop = determineStartStopStep(theSlice.stop,step,self.__length,-1)
currentNode = self.__getNodeAtPosition(start)
gettingNext = step > 0
absStep = abs(step)
for eachItem in range(start,stop,step):
retList.append(currentNode)
if eachItem + step <= stop:#prevents step from going out of bounds
for i in range(absStep):
currentNode = currentNode.get(gettingNext)
return retList
def __getNodeAtPosition(self, index):
'''(Private) Gets a Node at a given index'''
movingForward = index < (self.__length//2)-1
if movingForward:
currentNode = self.__first
toAdd = 1
else:
currentNode = self.__last
index = (self.__length-1) - index
toAdd = 0
"""
Putting the for loop inside the condition would reduce the amount
of times the conditon must be evaluated, increasing efficiency
But would also simultaneously increase the amount of repeated code
"""
for i in range(index+toAdd):
currentNode = currentNode.get(movingForward)
return currentNode
def __checkIndex(self, index):
'''(Private) check if the index is an acceptable value. Index only changes if negative'''
if type(index) != int:
raise TypeError("Index must be an integer or a slice not a "+str(type(index)).split("'")[1])
#handles negative indices.
if index < 0:
index += self.__length
#If the index is out of bounds
if index >= self.__length or index < 0:
raise IndexError("Index out of bounds")
return index
if __name__ == "__main__":
import random
def advanceWMessage(message):
input(message+" press enter to continue")
def printList(theList):
print("Current List:"+str(theList))
x = LinkedList()
for i in range(30):
x.append(i)
printList(x)
advanceWMessage("Testing slicing")
for i in range(10):
val1 = random.randint(0,len(x)//2)
val2 = random.randint(len(x)//2,len(x))
val3 = random.randint(1,len(x)//10)
print("\n\nstart: "+str(val1))
print("stop: "+str(val2))
print("step: "+str(val3))
print(x[val1:val2:val3])
advanceWMessage("Insert -1 at beginning")
x.insert(0,-1)
printList(x)