forked from 2016102050016/Imooc-Algorithm-PythonEdition
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrepo.py
More file actions
1087 lines (948 loc) · 32.3 KB
/
repo.py
File metadata and controls
1087 lines (948 loc) · 32.3 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
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
# -*- coding: utf-8 -*-
from random import randint
import re
import sys
#由于本人比较懒,把课程需要调用的代码全都堆到这一个文件里了,不太利于阅读,抱歉。。。
#不过,这里的代码是严格按照课程顺序的。
#强烈推荐使用Ctrl+F来查找对应的代码
'''Queue'''#只是因为后面有算法需要使用队列,我才在这里实现了一个队列的。对其他基础数据结构的实现不在此课程范围内。
class Queue:
def __init__(self):
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)
def __contains__(self, k):
return k in self.items
'''BubbleSort'''
def bubbleSort(alist):
exchange=False
for i in range(len(alist)-1,0,-1):
for j in range(i):
if alist[j]>alist[j+1]:
alist[j],alist[j+1]=alist[j+1],alist[j]
exchange=True
if not exchange:
break
return alist
'''SelectionSort'''
def selectionSort(alist):
for i in range(len(alist)):
minposition=i
for j in range(i,len(alist)):
if alist[minposition]>alist[j]:
minposition=j
alist[i],alist[minposition]=alist[minposition],alist[i]
return alist
'''InsertionSort'''
def insertionSort(alist):
for i in range(1,len(alist)):
currentvalue=alist[i]
position=i
while alist[position-1]>currentvalue and position>0:
alist[position]=alist[position-1]
position=position-1
alist[position]=currentvalue
return alist
'''ShellSort'''
def shellSort(alist):
gap=len(alist)//2
while gap>0:
for startpos in range(gap):
gapInsertionSort(alist,startpos,gap)
gap=gap//2
return alist
def gapInsertionSort(alist,startpos,gap):
for i in range(startpos+gap,len(alist),gap):
position=i
currentvalue=alist[i]
while position>=gap and alist[position-gap]>currentvalue:
alist[position]=alist[position-gap]
position=position-gap
alist[position]=currentvalue
'''MergeSort'''
def mergeSort(alist):
if len(alist)>1:
if len(alist)<=16:
alist=insertionSort(alist)
return alist
mid=len(alist)//2
lefthalf=alist[:mid]
righthalf=alist[mid:]
lefthalf=mergeSort(lefthalf)
righthalf=mergeSort(righthalf)
if lefthalf[-1] <= righthalf[0]:
alist=lefthalf+righthalf
return alist
i,j,k=0,0,0
while i<len(lefthalf) and j<len(righthalf):
if lefthalf[i]<=righthalf[j]:
alist[k]=lefthalf[i]
i+=1
else:
alist[k]=righthalf[j]
j+=1
k+=1
while i<len(lefthalf):
alist[k]=lefthalf[i]
k+=1
i+=1
while j<len(righthalf):
alist[k]=righthalf[j]
k+=1
j+=1
return alist
'''QuickSort2ways'''
def quickSort(alist):
quickSortHelper(alist,0,len(alist)-1)
return alist
def quickSortHelper(alist,first,last):
if first<last:
if last - first <= 16:
insertionSortForQS(alist, first, last)
else:
splitpoint=partition(alist,first,last)
quickSortHelper(alist,first,splitpoint-1)
quickSortHelper(alist,splitpoint+1,last)
def partition(alist,first,last):
rand = randint(first, last)
alist[first],alist[rand]=alist[rand],alist[first]
pivotvalue=alist[first]
leftmark=first+1
rightmark=last
done=False
while not done:
while leftmark<=rightmark and alist[leftmark]<pivotvalue:
leftmark+=1
while rightmark>=leftmark and alist[rightmark]>pivotvalue:
rightmark-=1
if leftmark>rightmark:
done=True
else:
alist[leftmark],alist[rightmark]=alist[rightmark],alist[leftmark]
leftmark+=1
rightmark-=1
alist[first],alist[rightmark]=alist[rightmark],alist[first]
return rightmark
def insertionSortForQS(alist,first,last):
for i in range(first+1,last+1):
currentvalue=alist[i]
position=i
while position>first and alist[position-1]>currentvalue:
alist[position]=alist[position-1]
position=position-1
alist[position]=currentvalue
return alist
'''QuickSort3Ways'''
def quickSort3Ways(alist):
quickSort3WaysHelper(alist,0,len(alist)-1)
return alist
def quickSort3WaysHelper(alist,first,last):
if first<last:
if last - first <= 16:
insertionSortForQS(alist, first, last)
else:
ltEnd,gtStart=partition3Ways(alist,first,last)
quickSort3WaysHelper(alist,first,ltEnd)
quickSort3WaysHelper(alist,gtStart,last)
def partition3Ways(alist,first,last):
rand=randint(first,last)
alist[first], alist[rand] = alist[rand], alist[first]
pivolvalue=alist[first]
lt,i,gt=first,first+1,last+1
done=False
while not done:
if alist[i]<pivolvalue:
alist[lt+1],alist[i]=alist[i],alist[lt+1]
i+=1
lt+=1
elif alist[i]==pivolvalue:
i+=1
else:
alist[gt-1],alist[i]=alist[i],alist[gt-1]
gt-=1
if i>=gt:
done=True
alist[first],alist[lt]=alist[lt],alist[first]
lt-=1
return lt,gt
'''BinHeap'''
class MaxHeap(object):
def __init__(self,max=100000):
self.heapList=[0]
self.currentSize=0
self.maximum=max
def shiftUp(self,i):
currentvalue=self.heapList[i]
while i//2>0:
if self.heapList[i//2] < currentvalue:
self.heapList[i]=self.heapList[i//2]
i=i//2
else:
break
self.heapList[i]=currentvalue
def insert(self,k):
self.heapList.append(k)
self.currentSize+=1
self.shiftUp(self.currentSize)
if self.currentSize > self.maximum:
self.delFirst()
def shiftDown(self,i):
currentvalue=self.heapList[i]
while i*2<=self.currentSize:
mc=self.maxChild(i)
if currentvalue < self.heapList[mc]:
self.heapList[i]=self.heapList[mc]
i=mc
else:
break
self.heapList[i]=currentvalue
def maxChild(self,i):
if i*2+1>self.currentSize:
return i*2
else:
if self.heapList[i*2]>self.heapList[i*2+1]:
return i*2
else:
return i*2+1
def delFirst(self):
retval=self.heapList[1]
if self.currentSize==1:
self.currentSize-=1
self.heapList.pop()
return retval
self.heapList[1]=self.heapList[self.currentSize]
self.heapList.pop()
self.currentSize-=1
self.shiftDown(1)
return retval
def buildHeap(self,alist): #heapify
self.heapList=[0]+alist[:]
self.currentSize=len(alist)
i=self.currentSize//2
while i>0:
self.shiftDown(i)
i-=1
overflow=self.currentSize-self.maximum
for i in range(overflow):
self.delFirst()
def HeapSort(self,alist):
self.buildHeap(alist)
return [self.delFirst() for x in range(self.currentSize)]
def HeapSortInPlace(self,alist):
self.buildHeap(alist)
while self.currentSize>1:
self.heapList[1],self.heapList[self.currentSize]=self.heapList[self.currentSize],self.heapList[1]
self.currentSize-=1
self.shiftDown(1)
return self.heapList
class MinHeap(MaxHeap):
def __init__(self):
super(MaxHeap, self).__init__()
def shiftUp(self,i):
currentvalue=self.heapList[i]
while i//2 > 0:
if self.heapList[i//2] > currentvalue:
self.heapList[i]=self.heapList[i//2]
i//2
else:
break
self.heapList[i] = currentvalue
def shiftDown(self,i):
currentvalue=self.heapList[i]
while i*2<=self.currentSize:
mc=self.minChild(i)
if currentvalue > self.heapList[mc]:
self.heapList[i]=self.heapList[mc]
i=mc
else:
break
self.heapList[i]=currentvalue
def minChild(self,i):
if i*2+1>self.currentSize:
return i*2
else:
if self.heapList[i*2] <self.heapList[i*2+1]:
return i*2
else:
return i*2+1
'''IndexHeap'''
class IndexMaxHeap(object):
def __init__(self):
self.indexList=[0]
self.items={}
self.currentSize=0
def shiftUp(self,i):
currentvalue=self.items[self.indexList[i]]
currentindex=self.indexList[i]
while i//2>0:
if self.items[self.indexList[i//2]] < currentvalue:
self.indexList[i]=self.indexList[i//2]
i=i//2
else:
break
self.indexList[i]=currentindex
def insert(self,k,value):
self.indexList.append(k)
self.items[k]=value
self.currentSize+=1
self.shiftUp(self.currentSize)
def shiftDown(self,i):
currentvalue=self.items[self.indexList[i]]
currentindex=self.indexList[i]
while i*2<=self.currentSize:
mc=self.maxChild(i)
if currentvalue < self.items[self.indexList[mc]]:
self.indexList[i]=self.indexList[mc]
i=mc
else:
break
self.indexList[i]=currentindex
def maxChild(self,i):
if i*2+1>self.currentSize:
return i*2
else:
if self.items[self.indexList[i*2]]>self.items[self.indexList[i*2+1]]:
return i*2
else:
return i*2+1
def delFirst(self):
retval=self.items[self.indexList[1]]
del self.items[self.indexList[1]]
if self.currentSize==1:
self.currentSize-=1
self.indexList.pop()
return retval
self.indexList[1]=self.indexList[self.currentSize]
self.indexList.pop()
self.currentSize-=1
self.shiftDown(1)
return retval
def buildHeap(self,items):
self.items=items
self.indexList=[0]+list(self.items.keys())
self.currentSize=items.__len__()
i=self.currentSize//2
while i>0:
self.shiftDown(i)
i-=1
def getItem(self,i):
return self.items[i]
def maxItemIndex(self):
return self.indexList[1]
def change(self,k,newValue):
if k not in self.indexList:
raise Exception('%s is not exist!' % k)
self.items[k]=newValue
i=self.indexList.index(k)
self.shiftDown(i)
self.shiftUp(i)
return True
'''Priority Queue'''
class PriorityQueue(object):
def __init__(self):
self.heapArray=[(0,0)]
self.currentSize=0
def buildHeap(self,alist):
self.heapArray+=alist[:]
self.currentSize=len(alist)
i=self.currentSize//2
while i>0:
self.shiftDown(i)
i-=1
def insert(self,k):
self.heapArray.append(k)
self.currentSize+=1
self.shiftUp(self.currentSize)
def shiftUp(self,i):
while i>0:
if self.heapArray[i][0]<self.heapArray[i//2][0]:
self.heapArray[i],self.heapArray[i//2]=self.heapArray[i//2],self.heapArray[i]
i=i//2
def delMin(self):
retval=self.heapArray[1][1]
self.heapArray[1]=self.heapArray[self.currentSize]
self.heapArray.pop()
self.currentSize-=1
self.shiftDown(1)
return retval
def shiftDown(self,i):
while i*2<=self.currentSize:
mc=self.minChild(i)
if self.heapArray[i][0]>self.heapArray[mc][0]:
self.heapArray[i],self.heapArray[mc]=self.heapArray[mc],self.heapArray[i]
i=i*2
def minChild(self,i):
if i*2+1>self.currentSize:
return i*2
else:
if self.heapArray[i*2][0]<self.heapArray[i*2+1][0]:
return i*2
else:
return i*2+1
def isEmpty(self):
if self.currentSize == 0:
return True
else:
return False
def __contains__(self, vtx):
for pair in self.heapArray:
if pair[1] == vtx:
return True
return False
def change(self,dist,vtx):
done=False
i=1
while not done and i<=self.currentSize:
if self.heapArray[i][1]==vtx:
done=True
else:
i+=1
if done:
self.heapArray[i]=(dist,vtx)
self.shiftUp(i)
'''BinarySearch'''
def binarySearch(alist,item):
first=0
last=len(alist)-1
while first<=last:
mid=first+(last-first)//2
if alist[mid] == item:
return True
else:
if alist[mid]<item:
last=mid-1
else:
first=mid+1
return False
def binarySearchRecursion(alist,item):
if len(alist)==0:
return False
else:
mid=len(alist)//2
if alist[mid]==item:
return True
elif alist[mid]<item:
return binarySearchRecursion(alist[mid+1:],item)
else:
return binarySearchRecursion(alist[:mid],item)
'''BinarySearchTree'''
class TreeNode(object):
def __init__(self,key,value,parent=None,left=None,right=None):
self.key=key
self.value=value
self.leftChild=left
self.rightChild=right
self.parent=parent
self.nodeCount=1
self.balanceFactor = 0
self.isleftchild = False
self.isrightchild = False
def hasLeftChild(self):
return self.leftChild
def hasRightChild(self):
return self.rightChild
def isLeftChild(self):
return self.parent and self.parent.leftChild == self
def isRightChild(self):
return self.parent and self.parent.rightChild == self
def isRoot(self):
return not self.parent
def isLeaf(self):
return not (self.rightChild or self.leftChild)
def hasAnyChildren(self):
return self.rightChild or self.leftChild
def hasBothChildren(self):
return self.rightChild and self.leftChild
def addChildAttr(self):
if self.isLeftChild():
self.isleftchild=True
else:
self.isrightchild=True
def replaceNodeData(self,key,value,lc,rc):
self.key=key
self.value=value
self.leftChild=lc
self.rightChild=rc
if self.hasLeftChild():
self.leftChild.parent=self
if self.hasRightChild():
self.rightChild.parent=self
def spliceOut(self):
if self.isLeaf():
if self.isLeftChild():
self.parent.leftChild = None
else:
self.parent.rightChild = None
elif self.hasAnyChildren():
if self.hasLeftChild():
if self.isLeftChild():
self.parent.leftChild = self.leftChild
else:
self.parent.rightChild = self.leftChild
self.leftChild.parent = self.parent
else:
if self.isLeftChild():
self.parent.leftChild = self.rightChild
else:
self.parent.rightChild = self.rightChild
self.rightChild.parent = self.parent
def findSuccessor(self):
current = self.rightChild
while current.hasLeftChild():
current = current.leftChild
return current
def findPredecessor(self):
current = self.leftChild
while current.hasRightChild():
current = current.rightChild
return current
class BinarySearchTree(object):
def __init__(self):
self.root=None
self.size=0
def length(self):
return self.size
def __len__(self):
return self.size
def put(self,key,value):
if self.root:
self._put(key,value,self.root)
else:
self.root=TreeNode(key,value)
self.size=self.size + 1
def _put(self,key,value,currentNode):
if key<currentNode.key:
if currentNode.hasLeftChild():
self._put(key,value,currentNode.leftChild)
else:
currentNode.leftChild=TreeNode(key,value,parent=currentNode)
elif key==currentNode.key:
currentNode.value=value
else:
if currentNode.hasRightChild():
self._put(key,value,currentNode.rightChild)
else:
currentNode.rightChild=TreeNode(key,value,parent=currentNode)
def __setitem__(self, key, value):
self.put(key,value)
def get(self,key):
if self.root:
res=self._get(key,self.root)
if res:
return res.value
else:
return None
else:
return None
def _get(self,key,currentNode):
if currentNode is None:
return None
elif currentNode.key==key:
return currentNode
elif currentNode.key>key:
return self._get(key,currentNode.leftChild)
else:
return self._get(key,currentNode.rightChild)
def __getitem__(self, item):
return self.get(item)
def __contains__(self, item):
if self._get(item,self.root):
return True
else:
return False
def delete(self, key):
if self.size > 1:
nodeToRemove = self._get(key, self.root)
if nodeToRemove:
self.remove(nodeToRemove)
self.size = self.size - 1
else:
raise KeyError('Error, key not in tree')
elif self.size == 1 and self.root.key == key:
self.root = None
self.size = self.size - 1
else:
raise KeyError('Error, key not in tree')
def __delitem__(self, key):
self.delete(key)
def remove(self, currentNode):
if currentNode.isLeaf():
if currentNode == currentNode.parent.leftChild:
currentNode.parent.leftChild = None
else:
currentNode.parent.rightChild = None
elif currentNode.hasBothChildren():
succ = currentNode.findSuccessor()
succ.spliceOut()
currentNode.key = succ.key
currentNode.value = succ.value
else:
if currentNode.hasLeftChild():
if currentNode.isLeftChild():
currentNode.leftChild.parent = currentNode.parent
currentNode.parent.leftChild = currentNode.leftChild
elif currentNode.isRightChild():
currentNode.leftChild.parent = currentNode.parent
currentNode.parent.rightChild = currentNode.leftChild
else:
currentNode.replaceNodeData(currentNode.leftChild.key,
currentNode.leftChild.value,
currentNode.leftChild.leftChild,
currentNode.leftChild.rightChild)
else:
if currentNode.isLeftChild():
currentNode.rightChild.parent = currentNode.parent
currentNode.parent.leftChild = currentNode.rightChild
elif currentNode.isRightChild():
currentNode.rightChild.parent = currentNode.parent
currentNode.parent.rightChild = currentNode.rightChild
else:
currentNode.replaceNodeData(currentNode.rightChild.key,
currentNode.rightChild.value,
currentNode.rightChild.leftChild,
currentNode.rightChild.rightChild)
def preOrder(self):
self._preOrder(self.root)
def _preOrder(self,treeNode):
if treeNode:
print(treeNode.key)
self._preOrder(treeNode.leftChild)
self._preOrder(treeNode.rightChild)
def inOrder(self):
self._inOrder(self.root)
def _inOrder(self,treeNode):
if treeNode:
self._inOrder(treeNode.leftChild)
print(treeNode.key)
self._inOrder(treeNode.rightChild)
def postOrder(self):
self._postOrder(self.root)
def _postOrder(self,treeNode):
if treeNode:
self._postOrder(treeNode.leftChild)
self._postOrder(treeNode.rightChild)
print(treeNode.key)
def levelOrder(self):
q = Queue()
q.enqueue(self.root)
while q.size() > 0:
treeNode = q.dequeue()
print(treeNode.key)
if treeNode.leftChild:
q.enqueue(treeNode.leftChild)
if treeNode.rightChild:
q.enqueue(treeNode.rightChild)
def minimum(self):
node = self.root
while node.leftChild:
node = node.leftChild
return node.key
def maximum(self):
node=self.root
while node.rightChild:
node=node.rightChild
return node.key
def getFloorAndCeil(self,key):
return self._getFloorAndCeil(self.root,key,None,None)
def _getFloorAndCeil(self,currentNode,key,floor,ceil):
if currentNode:
if currentNode.key==key:
floor,ceil=key,key
return floor,ceil
else:
if currentNode.key<key:
floor=currentNode.key
return self._getFloorAndCeil(currentNode.rightChild,key,floor,ceil)
else:
ceil=currentNode.key
return self._getFloorAndCeil(currentNode.leftChild,key,floor,ceil)
else:
return floor,ceil
'''AVLTree'''
class AVLTree(BinarySearchTree):
def __init__(self):
super(AVLTree, self).__init__()
def _put(self, key, val, currentNode):
if key < currentNode.key:
if currentNode.hasLeftChild():
self._put(key, val, currentNode.leftChild)
else:
currentNode.leftChild = TreeNode(key, val, parent=currentNode)
self.updateBalance(currentNode.leftChild, insert=True)
else:
if currentNode.hasRightChild():
self._put(key, val, currentNode.rightChild)
else:
currentNode.rightChild = TreeNode(key, val, parent=currentNode)
self.updateBalance(currentNode.rightChild, insert=True)
def delete(self, key):
if self.size > 1:
nodeToRemove = self._get(key, self.root)
if nodeToRemove:
if nodeToRemove.hasBothChildren():
succ=nodeToRemove.findSuccessor()
succ.addChildAttr()
self.remove(nodeToRemove)
nodeToRemove=succ
else:
nodeToRemove.addChildAttr()
self.remove(nodeToRemove)
self.updateBalance(nodeToRemove,first2delete=True)
self.size = self.size - 1
else:
raise KeyError('Error, key not in tree')
elif self.size == 1 and self.root.key == key:
self.root = None
self.size = self.size - 1
else:
raise KeyError('Error, key not in tree')
def updateBalance(self, node, insert=False, delete=False, first2delete=False):
if node.balanceFactor > 1 or node.balanceFactor < -1:
self.rebalance(node)
return
if node.parent != None:
if insert:
if node.isLeftChild():
node.parent.balanceFactor += 1
elif node.isRightChild():
node.parent.balanceFactor -= 1
if node.parent.balanceFactor != 0:
self.updateBalance(node.parent, insert=True)
if first2delete:
recursion=False
if node.parent.balanceFactor != 0:
recursion=True
if node.isleftchild:
node.parent.balanceFactor -= 1
elif node.isrightchild:
node.parent.balanceFactor += 1
if recursion:
self.updateBalance(node.parent, delete=True)
if delete:
recursion = False
if node.parent.balanceFactor != 0:
recursion = True
if node.isLeftChild():
node.parent.balanceFactor -= 1
elif node.isRightChild():
node.parent.balanceFactor += 1
if recursion:
self.updateBalance(node.parent, delete=True)
def rebalance(self, node):
if node.balanceFactor < 0:
if node.rightChild.balanceFactor > 0:
self.rotateRight(node.rightChild)
self.rotateLeft(node)
else:
self.rotateLeft(node)
elif node.balanceFactor > 0:
if node.leftChild.balanceFactor < 0:
self.rotateLeft(node.leftChild)
self.rotateRight(node)
else:
self.rotateRight(node)
def rotateLeft(self, rotRoot):
newRoot = rotRoot.rightChild
rotRoot.rightChild = newRoot.leftChild
if newRoot.leftChild != None:
newRoot.leftChild.parent = rotRoot
newRoot.parent = rotRoot.parent
if rotRoot.isRoot():
self.root = newRoot
else:
if rotRoot.isLeftChild():
rotRoot.parent.leftChild = newRoot
else:
rotRoot.parent.rightChild = newRoot
newRoot.leftChild = rotRoot
rotRoot.parent = newRoot
rotRoot.balanceFactor = rotRoot.balanceFactor + 1 - min(newRoot.balanceFactor, 0)
newRoot.balanceFactor = newRoot.balanceFactor + 1 + max(rotRoot.balanceFactor, 0)
def rotateRight(self,rotRoot):
newRoot = rotRoot.leftChild
rotRoot.leftChild=newRoot.rightChild
if newRoot.rightChild != None:
newRoot.rightChild.parent=rotRoot
newRoot.parent=rotRoot.parent
if rotRoot.isRoot():
self.root=newRoot
else:
if rotRoot.isLeftChild():
rotRoot.parent.leftChild = newRoot
else:
rotRoot.parent.rightChild = newRoot
newRoot.rightChild=rotRoot
rotRoot.parent=newRoot
rotRoot.balanceFactor=rotRoot.balanceFactor -1 - max(newRoot.balanceFactor,0)
newRoot.balanceFactor=newRoot.balanceFactor -1 + min(rotRoot.balanceFactor,0)
'''UnionFind'''
class UnionFind(object):
def __init__(self,count):
self.count=count
self.rank=[1 for x in range(count)]
self.parent=[x for x in range(count)]
def find(self,p):
if p>=0 and p<self.count:
while p != self.parent[p]:
self.parent[p]=self.parent[self.parent[p]]
p=self.parent[p]
return p
else:
raise KeyError('Key not in parent')
def isConnected(self,p,q):
return self.find(p) == self.find(q)
def Union(self,p,q):
pRoot,qRoot=self.find(p),self.find(q)
if pRoot==qRoot:
return
if self.rank[pRoot]<self.rank[qRoot]:
self.parent[pRoot]=qRoot
elif self.rank[pRoot]>self.rank[qRoot]:
self.parent[qRoot]=pRoot
else:
self.parent[pRoot]=qRoot
self.rank[qRoot]+=1
'''Adjacency Matrix'''
class DenseGraph(object):
def __init__(self,n,directed=False):
self.n=n
self.m=0
self.directed=directed
self.martix=[[0 for i in range(n)] for i in range(n)]
def __str__(self):
for line in self.martix:
print(str(line))
return ''
def getNumberOfVertex(self):
return self.n
def getNumberOfEdge(self):
return self.m
def addEdge(self, v, w):
if 0<=v<self.n and 0<=w<self.n:
if self.hasEdge(v,w):
return
self.martix[v][w]=1
if self.directed is False:
self.martix[w][v]=1
self.m+=1
else:
raise Exception('Vertex not in the graph')
def hasEdge(self,v,w):
if 0<=v<self.n and 0<=w<self.n:
return self.martix[v][w]
else:
raise Exception('Vertex not in the graph')
'''Adjacency List'''
class Vertex(object):
def __init__(self,key):
self.id = key
self.connectedTo = {}
self.ccid = 0
self.dist = sys.maxsize
self.pred = None
self.isvisited = False
def addNeighbor(self,nbr,weight=0):
self.connectedTo[nbr] = weight
def __str__(self):
return str(self.id) + ' connectedTo: ' + str([x.id for x in self.connectedTo])
def getConnections(self):
return self.connectedTo.keys()
def getConnectionsId(self):
idList=[]
for k in self.connectedTo.keys():
idList.append(k.getId())
return sorted(idList)
def getConnectionsIdAndWeight(self):
idList = []
for k in self.connectedTo.keys():
idList.append(k.getId())
weightList=list(self.connectedTo.values())
return {idList[i]:weightList[i] for i in range(len(idList))}
def getWeight(self,nbr):
return self.connectedTo[nbr]
def getId(self):
return self.id
def getCCID(self):
return self.ccid
def setCCID(self,ccid):
self.ccid=ccid
def getPred(self):
return self.pred
def setPred(self,pred):
self.pred=pred