-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata_structures.py
More file actions
809 lines (671 loc) · 22.2 KB
/
data_structures.py
File metadata and controls
809 lines (671 loc) · 22.2 KB
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
class Stack:
def __init__(self):
self.items = []
def __str__(self):
return str(self.items)
def isempty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items) - 1]
def size(self):
return len(self.items)
class InsertQueue:
def __init__(self):
self.items = []
def __str__(self):
return str(self.items)
def isempty(self):
return self.items == []
def enqueue(self, item):
self.items.insert(0, item)
def dequeue(self):
return self.items.pop()
def size(self):
return len(self.items)
class AppendQueue:
def __init__(self):
self.items = []
def __str__(self):
return str(self.items)
def isempty(self):
return self.items == []
def enqueue(self, item):
self.items.append(item)
def dequeue(self):
return self.items.pop(0)
def size(self):
return len(self.items)
class StackQueue:
def __init__(self):
self.input = Stack()
self.output = Stack()
def __str__(self):
return '[' + str(self.input) + ', ' + str(self.output) + ']'
def isempty(self):
return self.input.isempty() and self.output.isempty()
def enqueue(self, item):
self.input.push(item)
def dequeue(self):
if self.output.isempty():
while not self.input.isempty():
self.output.push(self.input.pop())
return self.output.pop()
def size(self):
return self.input.size() + self.output.size()
class Deque:
def __init__(self):
self.items = []
def __str__(self):
return str(self.items)
def isempty(self):
return self.items == []
def append(self, item):
self.items.append(item)
def add(self, item):
self.items.insert(0, item)
def pop(self):
return self.items.pop()
def popleft(self):
return self.items.pop(0)
def size(self):
return len(self.items)
class LinkedStack:
def __init__(self):
self.items = UnorderedList()
def __str__(self):
return str(self.items)
def isempty(self):
return self.items.isempty()
def push(self, item):
self.items.add(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items.head.data
def size(self):
return self.items.length()
class LinkedQueue:
def __init__(self):
self.items = UnorderedList()
def __str__(self):
return str(self.items)
def isempty(self):
return self.items.isempty()
def enqueue(self, item):
self.items.add(item)
def dequeue(self):
return self.items.pop(self.size() - 1)
def size(self):
return self.items.length()
class LinkedDeque:
def __init__(self):
self.items = UnorderedList()
def __str__(self):
return str(self.items)
def isempty(self):
return self.items.isempty()
def append(self, item):
self.items.insert(self.size(), item)
def add(self, item):
self.items.add(item)
def pop(self):
return self.items.pop(self.size() - 1)
def popleft(self):
return self.items.pop()
def size(self):
return self.items.length()
class DoublyLinkedQueue:
def __init__(self):
self.items = DoublyLinkedList()
def __str__(self):
return str(self.items)
def isempty(self):
return self.items.isempty()
def enqueue(self, item):
self.items.add(item)
def dequeue(self):
return self.items.pop(-1)
def size(self):
return self.items.length()
class Node:
def __init__(self, item):
self.data = item
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def __str__(self):
"""Gets a printable string of the list."""
if self.head is None:
return '[]'
a_string = '['
current = self.head
while current is not None:
if isinstance(current.data, str):
a_string += "'" + current.data + "', "
else:
a_string += str(current.data) + ', '
current = current.next
return a_string[:-2] + ']'
def add(self, item):
"""Adds an item to the start of the list."""
node = Node(item)
node.next = self.head
self.head = node
def remove(self, item):
"""Removes the first occurrence of an item in a list."""
current = self.head
previous = None
while current is not None:
if current.data == item:
if previous is None:
self.head = current.next
else:
previous.next = current.next
break
previous = current
current = current.next
def search(self, item):
"""Checks to see if an item is in the list. Returns a bool."""
current = self.head
while current is not None:
if current.data == item:
return True
current = current.next
return False
def isempty(self):
"""Checks to see if list is empty."""
return self.head is None
def length(self):
"""Traverses the entire list and returns list length."""
current = self.head
index = 0
while current is not None:
index += 1
current = current.next
return index
def index(self, item):
"""Takes an item and finds the index of the item in the list."""
current = self.head
index = 0
while current is not None:
if current.data == item:
return index
current = current.next
index += 1
def get(self, position):
"""Takes an index and returns the item in that list index."""
index = 0
current = self.head
while current is not None:
if index == position:
return current
current = current.next
index += 1
def pop(self, position=0):
"""Pops an item from the list. If no position is provided, pop's head."""
current = self.head
previous = None
index = 0
if not isinstance(position, int) or position < 0:
raise TypeError('Error: Inputs can only be of a positive integer data type.')
elif position == 0 and current is not None:
temp = self.head.data
self.head = self.head.next
return temp
while current is not None:
if position == index:
break
previous = current
current = current.next
index += 1
if current is None and index <= position:
raise IndexError(f'Error: Index out of range for popping item.')
temp = current.data
previous.next = current.next
return temp
def slice(self, start, stop):
"""Takes 2 integer inputs and returns an unordered linked list with nodes between those inputs."""
current = self.head
sliced_list = UnorderedList()
index = 0
if (not isinstance(start, int) or not isinstance(stop, int)) or (start < 0 or stop < 0):
raise TypeError('Error: Inputs can only be of a positive integer data type.')
elif start >= stop or self.head is None:
return sliced_list
while current is not None:
if stop == index:
break
elif start <= index:
sliced_list.add(current.data)
current = current.next
index += 1
if stop != index:
raise IndexError('Error: Slice index is out of range.')
sliced_list.reverse()
return sliced_list
def reverse(self):
"""Reverses the linked list."""
previous = None
current = self.head
nex = current.next
while current is not None:
current.next = previous
previous = current
current = nex
if nex is not None:
nex = nex.next
self.head = previous
class UnorderedList(LinkedList):
def __init__(self):
super().__init__()
def append(self, item):
"""Adds an item to the end of the list."""
current = self.head
if self.head is None:
self.head = Node(item)
return
while current.next is not None:
current = current.next
current.next = Node(item)
def insert(self, position, item):
"""Takes an item and a position and inserts that item as a node in the list."""
node = Node(item)
current = self.head
previous = None
index = 0
if not isinstance(position, int) or position < 0:
raise TypeError('Error: Position of insert can only be of a positive integer data type.')
elif self.head is None or position == 0:
return self.add(item)
while current is not None:
if index == position:
break
previous = current
current = current.next
index += 1
if current is None and index != position:
raise IndexError(f'Error: Index out of range for position of insert.')
node.next = previous.next
previous.next = node
class OrderedList(LinkedList):
def __init__(self):
super().__init__()
def add(self, item):
"""Adds an item in the ordered position in the list. Can stop early."""
current = self.head
previous = None
node = Node(item)
while current is not None:
if current.data > item:
break
previous = current
current = current.next
if previous is None:
node.next = self.head
self.head = node
return
node.next = current
previous.next = node
def remove(self, item):
"""Removes the first occurrence of an item in a list. Can stop early."""
current = self.head
previous = None
while current is not None:
if current.data == item:
if previous is None:
self.head = current.next
else:
previous.next = current.next
break
elif current.data > item:
break
previous = current
current = current.next
def search(self, item):
"""Checks to see if an item is in the list. Returns a bool. Can stop early."""
current = self.head
while current is not None:
if current.data == item:
return True
elif current.data > item:
break
current = current.next
return False
def index(self, item):
"""Takes an item and finds the index of the item in the list. Can stop early."""
current = self.head
index = 0
while current is not None:
if current.data == item:
return index
elif current.data > item:
return
current = current.next
index += 1
class DoublyNode:
def __init__(self, item):
self.data = item
self.next = None
self.back = None
def __str__(self):
return str(self.data)
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def __str__(self):
"""Gets a printable string of the list."""
if self.head is None:
return '[]'
a_string = '['
current = self.head
while current is not None:
if isinstance(current.data, str):
a_string += "'" + current.data + "', "
else:
a_string += str(current.data) + ', '
current = current.next
return a_string[:-2] + ']'
def add(self, item):
"""Adds an item to the start of the list."""
node = DoublyNode(item)
if self.head is not None:
self.head.back = node
else: # Means empty list
self.tail = node
node.next = self.head
self.head = node
def remove(self, item):
"""Removes the first occurrence of an item in a list."""
current = self.head
previous = None
while current is not None:
if current.data == item:
if previous is None: # Removing first item
self.head = current.next
if self.head is not None:
self.head.back = None
else:
self.tail = None
else: # Removing n item
previous.next = current.next
if current.next is not None:
current.next.back = previous
else:
self.tail = previous
break
previous = current
current = current.next
def search(self, item):
"""Checks to see if an item is in the list. Returns a bool."""
current = self.head
while current is not None:
if current.data == item:
return True
current = current.next
return False
def isempty(self):
"""Checks to see if list is empty."""
return self.head is None
def length(self):
"""Traverses the entire list and returns list length."""
current = self.head
index = 0
while current is not None:
index += 1
current = current.next
return index
def index(self, item):
"""Takes an item and finds the index of the item in the list."""
current = self.head
index = 0
while current is not None:
if current.data == item:
return index
current = current.next
index += 1
def get(self, position):
"""Takes an index and returns the item in that list index."""
index = 0
if position < 0:
current = self.tail
while current is not None:
index -= 1
if index == position:
return current
current = current.back
else:
current = self.head
while current is not None:
if index == position:
return current
current = current.next
index += 1
def pop(self, position=0):
"""Pops an item from the list. If no position is provided, pop's head."""
current = self.head
index = 0
if not isinstance(position, int):
raise TypeError('Error: Inputs can only be of an integer data type.')
elif position == 0 and current is not None:
temp = self.head.data
self.head = self.head.next
self.head.back = None
return temp
if position < 0:
current = self.tail
while current is not None:
index -= 1
if index == position:
break
current = current.back
else:
current = self.head
while current is not None:
if index == position:
break
current = current.next
index += 1
if current is None:
raise IndexError(f'Error: Index out of range for popping item.')
temp = current.data
if current.next is not None:
current.next.back = current.back
else:
self.tail = current.back
if current.back is not None:
current.back.next = current.next
else:
self.head = current.next
return temp
def slice(self, start, stop):
"""Takes 2 integer inputs and returns an unordered linked list with nodes between those inputs."""
# TODO: It is possible to accept negative values. It is possible to have start >= stop.
current = self.head
sliced_list = DoublyLinkedList()
index = 0
if (not isinstance(start, int) or not isinstance(stop, int)) or (start < 0 or stop < 0):
raise TypeError('Error: Inputs can only be of a positive integer data type.')
elif start >= stop or self.head is None:
return sliced_list
while current is not None:
if stop == index:
break
elif start <= index:
sliced_list.add(current.data)
current = current.next
index += 1
if stop != index:
raise IndexError('Error: Slice index is out of range.')
sliced_list.reverse()
return sliced_list
def reverse(self):
"""Reverses the linked list."""
previous = None
current = self.head
self.tail = current
temp = current.next
while current is not None:
current.next = previous
current.back = temp
previous = current
current = temp
if temp is not None:
temp = temp.next
self.head = previous
def append(self, item):
"""Similar to the add function, except backwards."""
current = self.tail
node = DoublyNode(item)
if self.head is None:
self.head = node
self.tail = node
return
current.next = node
node.back = current
self.tail = node
def insert(self, position, item):
"""Takes an item and a position and inserts that item as a node in the list."""
node = DoublyNode(item)
current = self.head
previous = None
index = 0
if not isinstance(position, int) or position < 0:
raise TypeError('Error: Position of insert can only be of a positive integer data type.')
elif self.head is None or position == 0:
return self.add(item)
while current is not None:
if index == position:
break
previous = current
current = current.next
index += 1
if current is None and index != position:
raise IndexError(f'Error: Index out of range for position of insert.')
node.next = previous.next
if node.next is not None:
node.next.back = node
else:
self.tail = node
previous.next = node
node.back = previous
def test_1():
"""Add and Remove functions work correctly."""
temp = DoublyLinkedList()
temp.add(10)
temp.add(20)
temp.add(30)
temp.add(40)
temp.add(50)
print(f'temp = {temp}')
print(f'temp.head = {temp.head}')
print(f'temp.head.next = {temp.head.next}')
print(f'temp.head.back = {temp.head.back}')
print(f'temp.tail = {temp.tail}')
print(f'temp.tail.next = {temp.tail.next}')
print(f'temp.tail.back = {temp.tail.back}')
temp.remove(10)
temp.remove(50)
temp.remove(30)
print(f'\ntemp = {temp}')
print(f'temp.head = {temp.head}')
print(f'temp.head.next = {temp.head.next}')
print(f'temp.head.back = {temp.head.back}')
print(f'temp.tail = {temp.tail}')
print(f'temp.tail.next = {temp.tail.next}')
print(f'temp.tail.back = {temp.tail.back}')
def test_2():
"""Index and Get functions work correctly."""
temp = DoublyLinkedList()
temp.add(10)
temp.add(20)
temp.add(30)
temp.add(40)
temp.add(50)
print(f'temp = {temp}')
print(f'temp.index(50) = {temp.index(50)}')
print(f'temp.index(40) = {temp.index(40)}')
print(f'temp.index(30) = {temp.index(30)}')
print(f'temp.index(20) = {temp.index(20)}')
print(f'temp.index(10) = {temp.index(10)}')
print(f'temp.get(0) = {temp.get(0)}')
print(f'temp.get(1) = {temp.get(1)}')
print(f'temp.get(2) = {temp.get(2)}')
print(f'temp.get(3) = {temp.get(3)}')
print(f'temp.get(4) = {temp.get(4)}')
print(f'temp.get(5) = {temp.get(5)}')
print(f'temp.get(-1) = {temp.get(-1)}')
print(f'temp.get(-2) = {temp.get(-2)}')
print(f'temp.get(-3) = {temp.get(-3)}')
print(f'temp.get(-4) = {temp.get(-4)}')
print(f'temp.get(-5) = {temp.get(-5)}')
print(f'temp.get(-6) = {temp.get(-6)}')
def test_3():
"""Pop() and Pop(index) functions work correctly."""
temp = DoublyLinkedList()
temp.add(10)
temp.add(20)
temp.add(30)
temp.add(40)
temp.add(50)
temp.add(60)
temp.add(70)
print(f'temp = {temp}')
print(f'temp.pop() = {temp.pop()}')
print(f'temp.pop(-2) = {temp.pop(-2)}')
print(f'temp.pop(0) = {temp.pop(0)}')
print(f'temp.pop(3) = {temp.pop(3)}')
print(f'\ntemp = {temp}')
print(f'temp.head = {temp.head}')
print(f'temp.head.next = {temp.head.next}')
print(f'temp.head.back = {temp.head.back}')
print(f'temp.tail = {temp.tail}')
print(f'temp.tail.next = {temp.tail.next}')
print(f'temp.tail.back = {temp.tail.back}')
def test_4():
"""Slice and Reverse functions work correctly."""
temp = DoublyLinkedList()
temp.add(10)
temp.add(20)
temp.add(30)
temp.add(40)
temp.add(50)
sliced = temp.slice(1, 4)
print(f'temp = {sliced}')
print(f'temp.reverse = {sliced.reverse()}')
print(f'temp = {sliced}')
print(f'temp.head = {sliced.head}')
print(f'temp.head.next = {sliced.head.next}')
print(f'temp.head.back = {sliced.head.back}')
print(f'temp.tail = {sliced.tail}')
print(f'temp.tail.next = {sliced.tail.next}')
print(f'temp.tail.back = {sliced.tail.back}')
def test_5():
"""Append and Insert functions work correctly."""
temp = DoublyLinkedList()
temp.append(20)
temp.insert(1, 30)
temp.insert(0, 10)
temp.append(40)
temp.add(0)
temp.insert(0, -10)
temp.insert(6, 50)
print(f'temp = {temp}')
print(f'temp.head = {temp.head}')
print(f'temp.head.next = {temp.head.next}')
print(f'temp.head.back = {temp.head.back}')
print(f'temp.tail = {temp.tail}')
print(f'temp.tail.next = {temp.tail.next}')
print(f'temp.tail.back = {temp.tail.back}')
run_test = False
if run_test:
test_1()
test_2()
test_3()
test_4()
test_5()