-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAlgorithmLibrary.py
1623 lines (1449 loc) · 60.2 KB
/
AlgorithmLibrary.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
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
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Algorithm Library (Python v3.12.2+)
Implemented by Cory Ye
For personal educational review.
"""
import heapq
import math
import random
import sys
from abc import ABC, ABCMeta, abstractmethod
from collections.abc import Callable, MutableSequence, Hashable
from typing import Any, TypeVar, Iterable
class TrieTagger:
"""
Trie-based entity tagger to tag all instances of a library
of string entities in a provided document string.
Suppose N is the token length of a document, M is the size of the
library of entities, and K is the token length of the longest
entity in the library. Then the insertion time complexity is O(MK)
from iteratively adding M entities with K length into the Trie,
and the matching time complexity is O(NK) from iteratively searching
for K length entities starting at each token in the document.
Combined, this takes O(MK + NK) time and up to O(MK) space.
"""
class TrieNode:
"""
TrieNode that stores a token, matches that terminate at the token,
and links to further tokens in the Trie.
"""
def __init__(self, token: str):
self.token = token
self.trieMatches = set()
self.trieNodes = {}
def getToken(self):
# Retrieve token represented by this TrieNode.
return self.token
def getTrieLeaves(self) -> set[str]:
# Retrieve all matches that terminate at self.token.
return self.trieMatches
def addTrieLeaf(self, matchEntity: str):
# Add match string terminates at self.token.
self.trieMatches.add(matchEntity)
def getTrieNode(self, token: str):
# For the token, return the child TrieNode.
# If not found, return None.
return self.trieNodes.get(token, None)
def addTrieNode(self, trieNode):
# Map token to child TrieNode for searching.
newToken = trieNode.getToken()
if newToken not in self.trieNodes:
self.trieNodes[newToken] = trieNode
class TrieEntity:
"""
Wrapper class for tokenized and matched entities
via tokenization or searching the Trie.
"""
def __init__(self, entity: str, startIdx: int, endIdx: int):
self.entity = entity
self.start = startIdx
self.end = endIdx
def __hash__(self):
# Compute hash for TrieMatch.
p = 31
hashData: list[Hashable] = [self.entity, self.start, self.end]
return sum([x.__hash__() * pow(p, i) for i, x in enumerate(hashData)])
def __repr__(self):
return f"{{Entity: {self.entity}, Start Index: {self.start}, End Index: {self.end}}}"
def getEntity(self) -> str:
return self.entity
def getStartIdx(self) -> int:
return self.start
def getEndIdx(self) -> int:
return self.end
class Tokenizer(ABC):
"""
Abstract base class for Tokenizers.
"""
@abstractmethod
def tokenize(self, doc: str):
"""
Tokenize a string into a list of TrieEntity.
"""
class CharTokenizer(Tokenizer):
"""
Tokenizer that splits documents into characters.
Default Tokenizer if no other Tokenizer is specified.
"""
@staticmethod
def tokenize(doc: str):
"""
Tokenize document into non-empty characters.
"""
return [TrieTagger.TrieEntity(c, i, i+1) for i, c in enumerate(doc)]
class WordTokenizer(Tokenizer):
"""
Tokenizer that splits documents into words, i.e.
sequences of characters bounded by whitespace.
"""
SPACE = " "
@classmethod
def tokenize(cls, doc: str):
"""
Tokenize document into non-empty word strings.
"""
tokenList = []
spaceSplit = doc.split(cls.SPACE)
posIdx = 0
for w in spaceSplit:
if w:
# Append new TrieEntity.
tokenList.append(TrieTagger.TrieEntity(w, posIdx, posIdx + len(w)))
# Increment posIdx by len(w) + 1.
posIdx += len(w) + 1
else: # Skip empty strings.
# Increment posIdx by 1 for a single whitespace.
posIdx += 1
# Return tokenized document.
return tokenList
def __init__(self, entityList: list[str], tokenizer: Tokenizer = None):
"""
Instantiate the TrieTagger.
"""
# Setup tokenizer.
self.tokenizer: TrieTagger.Tokenizer = tokenizer
# Root of the Trie.
self.root: TrieTagger.TrieNode = TrieTagger.TrieNode("")
# Insert all matchStrings into the Trie.
self.insertEntity(entityList)
def tokenize(self, doc: str) -> list[str]:
"""
Executes the configured tokenizer for the TrieTagger.
"""
if self.tokenizer is not None:
# Utilize specified Tokenizer.
return self.tokenizer.tokenize(doc)
else:
# Default to Character Tokenizer.
return TrieTagger.CharTokenizer.tokenize(doc)
def tag(self, document: str):
"""
Tag and identify all entities detected in the document
that have been registered into the TrieTagger.
"""
# Tokenize the document.
docTokens: list[TrieTagger.TrieEntity] = self.tokenize(document)
# Iterate through all starting tokens of the document.
trieMatches = []
for i in range(len(docTokens)):
# Search for TrieNodes in the Trie. Track position in document.
tokenIdx = 0
startIdx = docTokens[i].getStartIdx()
curNode = self.root
while i + tokenIdx < len(docTokens):
# Retrieve the token and TrieNode.
tokenEntity: TrieTagger.TrieEntity = docTokens[i+tokenIdx]
tokenNode: TrieTagger.TrieNode = curNode.getTrieNode(tokenEntity.getEntity())
# Terminate search if no more matched tokens.
if tokenNode is None:
break
# Append terminal TrieMatch to the output list.
trieMatches.extend([
TrieTagger.TrieEntity(e, startIdx, tokenEntity.getEndIdx())
for e in tokenNode.getTrieLeaves()
])
# Continue traversing the Trie.
curNode = tokenNode
# Increment token index.
tokenIdx += 1
# Return all matched entities in the Trie.
return trieMatches
def insertEntity(self, entityList: list[str]):
"""
Insert all strings in entityList into the Trie.
"""
# Insert all entities into the Trie.
for entity in entityList:
# Tokenize.
tokenEntityList = self.tokenize(entity)
# Sift through the Trie.
tokenIdx = 0
curNode = self.root
while tokenIdx < len(tokenEntityList):
# Retrieve the token and TrieNode.
tokenEntity: TrieTagger.TrieEntity = tokenEntityList[tokenIdx]
tokenNode = curNode.getTrieNode(tokenEntity.getEntity())
# Existing token.
if tokenNode is not None:
# Continue traversing the Trie.
curNode = tokenNode
else: # New token!
# Create new TrieNode.
newNode = TrieTagger.TrieNode(tokenEntity.getEntity())
# Map current TrieNode to new TrieNode.
curNode.addTrieNode(newNode)
# Continue traversing the Trie.
curNode = newNode
# Move to next token to insert.
tokenIdx += 1
# Reached the end of the entity, add the entity
# as a TrieMatch in the terminal token's TrieNode.
curNode.addTrieLeaf(entity)
class HeapCache:
"""
Implementation of an ordered cache / HeapCache, such that
the cache pops the min-order or max-order data when the cache
no longer has the capacity. When reverse=False, this implements
a min heap, and when reverse=True, this implements a max heap.
For example, HeapCache(reverse=False) where the order represents
timestamps implements a least-recently used cache (LRUCache).
Supports "static" use cases of internal methods if an external
cache and KV are provided.
"""
class Data:
"""
Generic Dataclass for HeapCache.
"""
def __init__(self, key: Hashable, data, order, index=None):
self.key = key
self.data = data
self.order = order
self.index = index
def getKey(self):
return self.key
def getData(self):
return self.data
def setData(self, data):
self.data = data
def getOrder(self):
return self.order
def setOrder(self, order):
self.order = order
def getIndex(self):
return self.index
def setIndex(self, index):
self.index = index
def __init__(self, reverse=False, capacity=None):
"""
Instantiate the KV store and Heap.
"""
self.KV = {}
self.heapCache = []
self.reverse = reverse
self.capacity = capacity
def __repr__(self, rawHeap=True):
"""
String representation of the heap.
"""
if rawHeap:
# Print raw heap without sorting.
return str([f"({x.getKey()}, {x.getData()}, {x.getOrder()}, {x.getIndex()})" for x in self.heapCache])
else:
# HeapSort
return str([f"({data.getData()}, {data.getOrder()})" for data in self.heapsort()])
def heapsort(self, kv: dict = None):
"""
Execute HeapSort.
"""
# Custom KV associated with a HeapCache.
keyValue = self.KV if kv is None else kv
# Execute HeapSort.
cacheCopy = []
kvCopy = {}
# Clone the HeapCache.
for key, value in sorted(keyValue.items(), key=lambda x: x[1].getIndex(), reverse=False):
kvCopy[key] = self.Data(key, value.getData(), value.getOrder(), value.getIndex())
cacheCopy.append(kvCopy[key])
# Sort.
output = []
while cacheCopy:
output.append(self.popData(cache=cacheCopy, kv=kvCopy))
return output
def insertData(self, key: Hashable, value, order: int, cache: list = None, kv: dict = None):
"""
Insert data into HeapCache. If an existing data with the
same key already exists, overwrite the data from the heap.
Furthermore, if the capacity of the HeapCache is specified
and is exceeded, pop an element from HeapCache.
"""
# Custom cache and KV.
heapCache = self.heapCache if cache is None else cache
keyValue = self.KV if kv is None else kv
# Check if key exists in KV / Heap.
if key in keyValue:
# Overwrite.
keyValue[key].setData(value)
keyValue[key].setOrder(order)
# Re-heapify.
self.sift(keyValue[key].getIndex(), cache=heapCache)
else:
# Create new Data.
data = self.Data(key, value, order, index=len(heapCache))
# Insert into KV.
keyValue[key] = data
# Append to HeapCache.
heapCache.append(data)
# Sift up.
self.sift(data.getIndex(), cache=heapCache)
# Capacity checking.
if isinstance(self.capacity, int) and len(heapCache) > self.capacity:
overflow = len(heapCache) - self.capacity
for _ in range(overflow):
# Pop element from heap.
self.popData(cache=heapCache, kv=keyValue)
def popData(self, key: Hashable = None, cache: list = None, kv: dict = None):
"""
Pop specified element and heapify. If no key is provided,
then pop the initial element of the heap.
"""
# Custom cache and KV.
heapCache = self.heapCache if cache is None else cache
keyValue = self.KV if kv is None else kv
if not heapCache:
# Empty HeapCache. Return None.
return None
# Pop specific key from HeapCache and KV.
targetIdx = 0
if key in keyValue:
# Search heap index by key.
targetIdx = keyValue[key].getIndex()
# Pop key from KV.
keyValue.pop(key)
elif key is None:
# Search key by heap index.
key = heapCache[targetIdx].getKey()
# Pop key from KV.
keyValue.pop(key)
else:
# Key is specified but does not exist. Do nothing.
return None
# Identify element at the specified index of the heap.
data = heapCache[targetIdx]
# Heapify (if there exists at least one child).
if len(heapCache)-1 > targetIdx:
# Swapping with the bottom of
# the heap preserves indices.
heapCache[targetIdx] = heapCache.pop()
heapCache[targetIdx].setIndex(targetIdx)
# Sift down if children exist.
self.sift(targetIdx, cache=heapCache)
else:
# Empty the first and only element from the heap.
heapCache.pop(targetIdx)
# Return data.
return data
def heapify(self, cache: list = None):
"""
Heapify the cache.
"""
# Custom cache and KV.
heapCache = self.heapCache if cache is None else cache
# Heapify via iterative sift down.
for i in range(len(heapCache)-1, -1, -1):
# Sift down from the end of the heap.
self.sift(i, cache=heapCache)
def sift(self, siftIdx: int, cache: list = None):
"""
Initiate a bi-directional sift operation optionally starting at siftIdx.
If the parent violates the heap, sift up. If a child violates the heap, sift down.
Update swapped indices along the way.
"""
# Custom cache and KV.
heapCache = self.heapCache if cache is None else cache
# Sift up or down to heapify.
while siftIdx >= 0 and siftIdx < len(heapCache):
# Compute least- or most-recently used data in binary heap.
swapIdx = siftIdx
for adjIdx in [2*siftIdx+1, 2*siftIdx+2, math.floor((siftIdx - 1) / 2)]:
if adjIdx < 0 or adjIdx >= len(heapCache):
# No children or no parent.
continue
elif any([
not self.reverse and any([
# Parent has higher order than child, which requires sifting.
adjIdx < swapIdx and heapCache[adjIdx].getOrder() > heapCache[swapIdx].getOrder(),
# Child has lower order than parent, which requires sifting.
adjIdx > swapIdx and heapCache[adjIdx].getOrder() < heapCache[swapIdx].getOrder()
]),
self.reverse and any([
# Parent has lower order than child, which requires sifting.
adjIdx < swapIdx and heapCache[adjIdx].getOrder() < heapCache[swapIdx].getOrder(),
# Child has higher order than parent, which requires sifting.
adjIdx > swapIdx and heapCache[adjIdx].getOrder() > heapCache[swapIdx].getOrder()
])
]):
# Identify higher or lower order data.
swapIdx = adjIdx
if swapIdx != siftIdx:
# Sift.
heapCache[swapIdx], heapCache[siftIdx] = heapCache[siftIdx], heapCache[swapIdx]
# Update indices for insertion and deletion at O(log(n)).
heapCache[swapIdx].setIndex(swapIdx)
heapCache[siftIdx].setIndex(siftIdx)
# Iterate in the direction of the sift. Will converge or break.
siftIdx = swapIdx
else:
# No swap necessary, so heap property is satisfied.
break
class QuickSort:
"""
QuickSort implementation with Lomuto "median-of-three" partitioning.
"""
class Comparable(metaclass=ABCMeta):
"""
ABC for enforcing __lt__ comparability.
"""
@abstractmethod
def __lt__(self, other: Any) -> bool: ...
CT = TypeVar("CT", bound=Comparable)
@staticmethod
def sort(seq: MutableSequence[CT], reverse: bool = False):
"""
Static function for executing in-place QuickSort on the MutableSequence provided.
"""
if seq:
# Instantiate QuickSort boundaries.
low = 0
high = len(seq) - 1
# QuickSort
QuickSort.quicksort(seq, low, high)
if reverse:
seq.reverse()
@staticmethod
def quicksort(seq: MutableSequence[CT], low: int, high: int):
"""
Recursive Lomuto "median-of-three" QuickSort implementation.
:param seq <MutableSequence<CT>>: Sequence of ComparableType that have defined ordering.
:param low <int>: Index of lower bound of sorting scope.
:param high <int>: Index of upper bound of sorting scope.
"""
# Continuation criteria.
if low >= 0 and high >= 0 and low < high:
# Partition.
lt, gt = QuickSort.partition(seq, low, high)
# Sort lower partition.
QuickSort.quicksort(seq, low, lt-1)
# Sort upper partition.
QuickSort.quicksort(seq, gt+1, high)
@staticmethod
def partition(seq: MutableSequence[CT], low: int, high: int):
"""
Partition sequence into elements less or greater than a median-of-three pivot.
:param seq <MutableSequence<CT>>: Sequence of ComparableType that have defined ordering.
:param low <int>: Index of lower bound of sorting scope.
:param high <int>: Index of upper bound of sorting scope.
"""
# Compute median pivot and swap to mid.
mid = math.floor(low + (high - low) / 2) # To avoid integer overflow from adding low and high.
QuickSort.centerMedian(seq, low, mid, high)
median = seq[mid]
# Swap the elements around the pivot.
lt = low # Lowest upper bound of the lesser partition.
eq = low # Lowest upper bound of the equivalent partition. Always lt <= eq.
gt = high # Greatest lower bound of the greater partition.
while eq <= gt:
if seq[eq] < median:
# Swap to lesser partition.
QuickSort.swap(seq, eq, lt)
# Extend the lesser partition boundary.
lt += 1
# Extend the equiv partition boundary to
# account for the new addition into the
# lesser partition which increments the
# position of the equiv partition.
eq += 1
elif seq[eq] > median:
# Swap to greater partition.
QuickSort.swap(seq, eq, gt)
# Extend the greater partition boundary.
gt -= 1
else: # seq[eq] == median
# Extend the equiv partition boundary.
eq += 1
# Return lowest upper bound and greatest lower bound of the unsorted sequence.
return lt, gt
@staticmethod
def centerMedian(seq: MutableSequence[CT], low: int, mid: int, high: int):
"""
Compute the median-of-three for low, mid and high in seq.
After sorting, the median is swapped into the mid spot.
:param seq <MutableSequence<CT>>: Sequence of ComparableType that have defined ordering.
:param low <int>: Lowest element.
:param mid <int>: Median element.
:param high <int>: Highest element.
"""
# Sort low, mid, and high in-place.
if seq[low] > seq[mid]:
# Swap low and mid.
QuickSort.swap(seq, low, mid)
if seq[mid] > seq[high]:
# Swap mid and high.
QuickSort.swap(seq, mid, high)
if seq[low] > seq[mid]:
# Swap low and mid (again).
QuickSort.swap(seq, low, mid)
@staticmethod
def swap(seq: MutableSequence[CT], left: int, right: int):
"""
Swap the elements at index left and right in-place.
:param seq <MutableSequence<CT>>: Sequence of ComparableType that have defined ordering.
:param left <int>: Index of left element.
:param right <int>: Index of right element.
"""
# Swap left and right.
seq[right], seq[left] = seq[left], seq[right]
class BinarySearchTree:
class Node:
def __init__(self, value = None):
self.data = value
self.left = None
self.right = None
def getData(self):
return self.data
def setData(self, data):
self.data = data
def getLeft(self):
return self.left
def setLeft(self, node):
self.left = node
def getRight(self):
return self.right
def setRight(self, node):
self.right = node
def __init__(self):
self.root = None
def __repr__(self):
# Print all elements of the BST.
return f"{self.sort()}"
def getRoot(self):
return self.root
def search(self, value):
# Find the node containing value.
return self._traverse(value, find=True)[0]
def insert(self, value):
# Empty tree.
if self.root is None:
# Insert node.
self.root = self.Node(value)
return
# Iterate through the binary search tree.
prevNode = self._traverse(value, find=False)[1]
# Insert leaf.
newNode = self.Node(value)
if prevNode.getData() > value:
# Attach new node to left of prevNode.
prevNode.setLeft(newNode)
else:
# Attach new node to right of prevNode.
prevNode.setRight(newNode)
def sort(self):
return self._sort(self.root)
def _traverse(self, value, find: bool = True):
"""
Traverse the binary search tree.
"""
# Iterate through the binary search tree.
curNode = self.root
prevNode = self.root
while curNode is not None:
# Compare with value at curNode.
if curNode.getData() == value and find:
return curNode, prevNode
elif curNode.getData() > value:
# Step into left sub-tree.
prevNode = curNode
curNode = curNode.getLeft()
else:
# Step into right sub-tree.
prevNode = curNode
curNode = curNode.getRight()
# Return curNode and prevNode.
return curNode, prevNode
def _sort(self, node):
if node is None:
return []
# Return in-order traversal representation.
return self._sort(node.getLeft()) + [node.getData()] + self._sort(node.getRight())
@classmethod
def isBST(cls, root) -> bool:
return cls._isBST(root)[0]
@classmethod
def _isBST(cls, root) -> tuple[bool, int, int]:
"""
Recursive implementation for BinarySearchTree validation.
"""
if root is None:
# Empty tree is BST.
return True, None, None
# Check if sub-trees are BST. Track sub-tree minimum and maximum values.
leftBST, rightBST = True, True
leftMin, leftMax, rightMin, rightMax = None, None, None, None
if root.getLeft() is not None:
leftBST, leftMin, leftMax = cls._isBST(root.getLeft())
if root.getRight() is not None:
rightBST, rightMin, rightMax = cls._isBST(root.getRight())
# Validate if tree is BST.
if all([
leftBST,
rightBST,
leftMax is None or root.getData() >= leftMax,
rightMin is None or root.getData() < rightMin
]):
# Compute minimum and maximum of validated BST.
treeMin = leftMin if leftMin is not None else root.getData()
treeMax = rightMax if rightMax is not None else root.getData()
return True, treeMin, treeMax
else:
# Invalid BST.
return False, None, None
class LinkedList:
"""
Linked list implementation with common transformations.
No practical use besides brain-teasing.
"""
class Node:
"""
LinkedList Node
"""
def __init__(self, data):
self.data = data
self.next = None
def __repr__(self):
return f"{self.data}"
def __init__(self):
"""
Instantiate (non-empty) LinkedList.
"""
self.head = self.Node("HEAD")
def __repr__(self):
"""
Print LinkedList.
"""
listOutput = []
nodeIter = self.head
while nodeIter is not None:
listOutput.append(nodeIter)
nodeIter = nodeIter.next
return " -> ".join([f"{x.data}" for x in listOutput])
def iterate(self, terminateCondition: Callable[..., bool]):
"""
Iterate until termination condition is satisfied.
"""
nodeIter = self.head
while nodeIter is not None and not terminateCondition(nodeIter):
nodeIter = nodeIter.next
return nodeIter
def append(self, node: Node):
"""
Append Node to LinkedList.
"""
# Search for the final node in the LinkedList.
finalNode = self.iterate(lambda x: x.next is None)
finalNode.next = node
return node
def delete(self, data):
"""
Delete the initial node containing data.
Return data if deleted, else return None.
"""
# Search for node before the node with matching data.
prevSearchNode = self.iterate(lambda x: x.next is not None and x.next.data == data)
# Delete the node if not None.
if prevSearchNode is not None:
prevSearchNode.next = prevSearchNode.next.next
return data
else:
# Iterated to the end of the LinkedList. Do not delete.
return None
def clear(self):
"""
Clear the LinkedList.
"""
# Create a new HEAD node.
self.head = self.Node("HEAD")
def swap(self, data1, data2):
"""
Swap two nodes in the LinkedList.
For example, swap(2,4) ~ swap(4,2) implies:
{1 -> [2] -> 3 -> [4] -> 5} => {1 -> [4] -> 3 -> [2] -> 5}
| ^
v |
{1 -> [2] 3 <> [4] 5} => {1 [2] <- 3 <- [4] 5}
|-----------------^ | |-----------------^
|-----------------^
"""
# Search for the nodes before the two nodes to swap.
prevFirstNode = self.iterate(lambda x: x.next is not None and x.next.data == data1)
prevSecondNode = self.iterate(lambda x: x.next is not None and x.next.data == data2)
if prevFirstNode is None or prevSecondNode is None:
# At least one of the nodes does not exist. Do nothing.
raise LookupError("At least one of the nodes specified does not exist and cannot be swapped.")
# Swap next node pointers.
tempFirstNext = prevFirstNode.next.next
prevFirstNode.next.next = prevSecondNode.next.next
prevSecondNode.next.next = tempFirstNext
# Swap prev node pointers.
tempFirst = prevFirstNode.next
prevFirstNode.next = prevSecondNode.next
prevSecondNode.next = tempFirst
def reverse(self):
"""
Reverse the LinkedList.
"""
# Iterate through the list, reversing each of the next pointers.
nodeIter = self.head.next
prevIter = None
nextIter = None
while nodeIter is not None:
# Save next node to iterate to.
nextIter = nodeIter.next
# Reverse direction of list.
nodeIter.next = prevIter
# Track current node as next previous node for reversal.
prevIter = nodeIter
# Iterate to next node.
nodeIter = nextIter
# Reset the HEAD node to point to the final previous node.
self.head.next = prevIter
class FibonacciCache:
"""
Compute all Fibonacci numbers. Optionally, cache them for future calculations.
"""
def __init__(self):
"""
Instantiate the FibonacciCache.
"""
self.fiboCache = {0: 0, 1: 1}
def __repr__(self):
"""
Print the largest Fibonacci number stored in this instance.
"""
return f"Fibonacci Cache Element Number {len(self.fiboCache)} : {self.fiboCache[len(self.fiboCache) - 1]}"
def fibonacci(self, n: int, cache: bool = True):
"""
Compute all Fibonacci numbers up to n.
:param n <int>: Compute the n-th Fibonacci number.
:param cache <bool>: Used cached implementation.
"""
if cache:
return self.cachedFibonacci(n)
else:
return self.recursiveFibonacci(n)
def cachedFibonacci(self, n: int):
"""
Compute Fibonacci numbers using a cache.
:param n <int>: Compute and cache n Fibonacci numbers.
"""
for i in range(n):
if i >= len(self.fiboCache):
# Inductively compute Fibonacci numbers.
self.fiboCache[i] = self.fiboCache[i-1] + self.fiboCache[i-2]
# Return requested Fibonacci number.
return self.fiboCache[len(self.fiboCache) - 1]
def recursiveFibonacci(self, n: int):
"""
Compute Fibonacci numbers via recursion.
:param n <int>: Compute the n-th Fibonacci number.
"""
if n == 0 or n == 1:
return n
else:
# Recursively compute Fibonacci numbers.
self.fiboCache[n] = self.recursiveFibonacci(n-1) + self.recursiveFibonacci(n-2)
return self.fiboCache[n]
class TarjanSCC:
"""
Compute all strongly-connected components in a directed graph G.
Utilizes Tarjan's strongly-connected components recursion DFS algorithm.
Returns a list of strongly-connected components sorted topologically.
"""
def __init__(self, graph):
"""
Instantiate graph information for strongly-connected component searching of G.
:param graph <list<list>>: Adjacency matrix for the graph G. Nodes are indexed by
non-negative integers, i.e. 0, 1, 2, ...
"""
self.G = graph # Adjacency Matrix for Graph
self.dfs = [] # Depth-First Search Stack
self.index = 0 # Exploration Index
self.D = { # Node Data
k: {
'index': None, # Track exploration index.
'minlink': None, # Track minimal sub-tree / reachable index.
'instack': False # Track DFS stack presence (for efficient lookup).
}
for k in range(len(graph))
}
def tarjan_dfs(self, reverse=False):
"""
Execute Tarjan's strongly-connected components algorithm. Sorted in topological order from source to sink.
:param reverse <bool>: Topological sort on list of SCC from sinks to sources instead of sources to sinks.
"""
# Search for strongly-connected components for all nodes in the graph.
SCC = []
for v in range(len(self.G)):
# Skip explored nodes.
if self.D[v]['index'] is None:
# Identify strongly-connected components associated with minimal reachable node v.
component = self.scc(v)
if component:
SCC.append(component)
# Topological Sort
if not reverse:
# Reverse the discovered list of SCC to sort
# in order from sources to sinks instead of
# sinks to sources in the graph G.
SCC.reverse()
# Output list of SCC.
return SCC
def scc(self, v):
"""
Identify strongly-connected components associated with the minimal reachable node v.
"""
# Process the node v. Set the exploration index,
# initialize the minlink index, and push into stack.
self.D[v]['index'] = self.index
self.D[v]['minlink'] = self.index
self.index += 1
self.dfs.append(v)
self.D[v]['instack'] = True
# Explore adjacent nodes.
for w in range(len(self.G[v])):
# Adjacent reachable nodes.
if self.G[v][w] != 0:
# Unexplored node.
if self.D[w]['index'] is None:
# Analyze strongly-connected sub-component of node w.
self.scc(w)
# Update the minimum exploration index reachable from w.
self.D[v]['minlink'] = min(
self.D[v]['minlink'],
self.D[w]['minlink']
)
# Explored node in the DFS stack. (Back-Edge Node)
elif self.D[w]['instack']:
# Update the minimum exploration index relative to
# the back-edge node index. Do NOT utilize the minimum
# reachable exploration index of the back-edge node,
# which considers minimum reachable exploration indices
# of the sub-trees of the back-edge node!
self.D[v]['minlink'] = min(
self.D[v]['minlink'],
self.D[w]['index']
)
# Output the SCC if the node is a minimal reachable node of the SCC.
scc_detect = []
if self.D[v]['minlink'] == self.D[v]['index']:
# Include nodes in the sub-tree of the minimal reachable node.
while self.dfs and self.D[self.dfs[-1]]['index'] >= self.D[v]['index']:
w = self.dfs.pop()
scc_detect.append(w)
self.D[w]['instack'] = False
return scc_detect
class DijkstraBFS:
def __init__(self, graph, maximal=False):
"""
Instantiate graph information for minimal breadth-first searching in Dijkstra's Algorithm.
:param graph <list<list>>: Adjacency matrix (with optional weights) for the graph G.
Nodes are indexed by non-negative integers, i.e. 0, 1, 2, ...
:param maximal <bool>: Return maximal path(s) / distance(s) instead.
"""
self.G = graph
extrema = float('inf') if not maximal else -float('inf')
self.dist = {
x: {
y: extrema if x != y else 0
for y in range(len(graph))
} for x in range(len(graph))
}
self.path = {
x: {
y: [] if x != y else [x]
for y in range(len(graph))
} for x in range(len(graph))
}
self.maximal = maximal
def bfs(self, initial_node=None):
"""
Perform a minimal (or maximal) breadth-first search of the graph G.
:param initial_node <int>: Initial node specification instead of processing entire graph.
"""
# Search from all initial nodes in case of directed or disconnected components.
task = list(range(len(self.G)))
if initial_node is not None and initial_node in task:
# Only search from the initial node instead. More efficient.
task = [initial_node]
for v in task:
# Reset queue and processed set.
heap = []
# FIFO Queue for BFS. Using a min heap
# to sort by edge weight.
heapq.heappush(
heap,
(0,v)
)
processed = set()
# BFS
while heap:
# Pop minimal node. Pre-emptively set node as processed.
_, a = heapq.heappop(heap)
processed.add(a)
# Search for adjacent nodes.
for b in range(len(self.G)):
if b != a and self.G[a][b] != 0:
# Update distance and path.
if any([
not self.maximal and self.dist[v][b] > self.dist[v][a] + self.G[a][b],
self.maximal and self.dist[v][b] < self.dist[v][a] + self.G[a][b]
]):
self.dist[v][b] = self.dist[v][a] + self.G[a][b]