-
Notifications
You must be signed in to change notification settings - Fork 0
/
combinedFiles.py
6226 lines (5085 loc) · 197 KB
/
combinedFiles.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
import numpy as np
class Node(object):
def __init__(self, key, val=None):
self.key = key
self.value = val
self.left = None
self.right = None
self.height = 0
class AVLTree(object):
def __init__(self, node=None):
self.root = node
def height(self, node):
if node is None:
return -1
return node.height
def rotate(self, node):
left_height = self.height(node.left)
right_height = self.height(node.right)
if left_height > right_height:
ll_height = self.height(node.left.left)
lr_height = self.height(node.left.right)
if ll_height > lr_height:
return self.rotateRight(node)
else:
node.left = self.rotateLeft(node.left)
return self.rotateRight(node)
else:
rl_height = self.height(node.right.left)
rr_height = self.height(node.right.right)
if rr_height > rl_height:
return self.rotateLeft(node)
else:
node.right = self.rotateRight(node.right)
return self.rotateLeft(node)
def rotateLeft(self, node):
right_node = node.right
node.right = right_node.left
right_node.left = node
node.height = max(self.height(node.left), self.height(node.right)) + 1
right_node.height = max(self.height(right_node.left), self.height(right_node.right)) + 1
return right_node
def rotateRight(self, node):
left_node= node.left
node.left = left_node.right
left_node.right = node
node.height = max(self.height(node.left), self.height(node.right)) + 1
left_node.height = max(self.height(left_node.left), self.height(left_node.right)) + 1
return left_node
def insertAtNode(self, node, key, value):
if node is None:
node = Node(key, value)
return node, node, True
if node.key == key:
node.value = value
return node, node, False
elif node.key > key:
node.left, nd, inserted = self.insertAtNode(node.left, key, value)
node.height = max(self.height(node.left), self.height(node.right)) + 1
if abs(self.height(node.left) - self.height(node.right)) > 1:
node = self.rotate(node)
return node, nd, inserted
else:
node.right, nd, inserted = self.insertAtNode(node.right, key, value)
node.height = max(self.height(node.left), self.height(node.right)) + 1
if abs(self.height(node.left) - self.height(node.right)) > 1:
node = self.rotate(node)
return node, nd, inserted
def insert(self, key, value=None):
vals = self.insertAtNode(self.root, key, value)
self.root = vals[0]
return vals[1:] # actual node inserted, bool
import numpy as np
class Node(object):
def __init__(self, attr, threshold, left_child=None, right_child=None):
self.attr = attr
self.threshold = threshold
self.left = left_child
self.right = right_child
class GBoostClassificDecTree(object):
def __init__(self, max_leaves):
self.maxLeaves = max_leaves
self.roots = []
def buildTree(self, inputs, outputs, features):
if len(features) == 0:
return None
feature = features[-1]
rem_feat = features[0:-1]
vals = sorted(list(set(inputs[:,feature])))
max_red = None
best_threshold = None
for threshold in vals:
gini_imp_red = self.getGiniImpuriyReduction(threshold, inputs[:, feature], y_out)
if (max_red is None) or (max_red < gini_imp_red):
max_red = gini_imp_red
best_threshold = threshold
# build the tree
node = Node(feature, best_theshold)
left_data = np.where(inputs[:, feature] <= best_threshold, True, False)
node.left, rem_feat = self.buildTree(inputs[left_data,:], outputs[left_data], rem_feat)
right_data = np.where(left_data, False, True)
node.right, rem_feat = self.buildTree(inputs[right_data, :], outputs[right_data], rem_feat)
return node, rem_feat
def constructTree(self, inputs, outputs):
ninp = inputs.shape[1]
max_levels = np.log2(ninp)
features = np.random.choice(ninp, size=max_levels, replace=False)
# assume categorical outputs, continuous inputs
# classification
output_types = list(set(outputs))
if len(output_types) > 2:
for output in output_types:
y_out = np.where(outputs == output, True, False)
self.roots.append(self.buildTree(inputs, y_out, features))
else:
y_out = np.where(outputs == output_types[0], True, False)
self.roots.append(self.buildTree(inputs, y_out, features))
import numpy as np
from collections import deque
class Edge(object):
def __init__(self, v, capacity, flow=0):
self.v = v
self.flow = flow
self.capacity = capacity
assert self.flow <= self.capacity
def __hash__(self):
return hash(self.v)
def __eq__(self, other):
return self.v == other.v
# graph is a dict of dict {u: {v: Edge(u->v)}}
# O(E^2V)
class EdmundKarp(object):
def BFS(self, graph, s, t):
queue = deque()
queue.append(s)
nvtx = len(graph)
parent = np.zeros(nvtx, dtype=np.int)
parent[:] = -1
parent[s] = -2
while len(queue):
vertex = queue.popleft()
for edge in graph.get(vertex, {}):
if (parent[edge.v] == -1) and (edge.capacity > edge.flow):
parent[edge.v] = vertex
queue.append(edge.v)
if edge.v == t:
break
return parent
def augmentflow(self, graph, s, t, parent):
v = t
min_flow = -1
while v != s:
u = parent[v]
edge = graph[u][v]
if (min_flow < 0) or (min_flow > edge.capacity - edge.flow):
min_flow = edge.capacity - edge.flow
v = u
v = t
while v != s:
u = parent[v]
edge = graph[u][v]
edge.flow += min_flow
# reverse edge
if v not in graph:
graph[v] = dict()
if u not in graph[v]:
graph[v][u] = Edge(u, edge.flow, 0)
graph[v][u].capacity = edge.flow
v = u
return min_flow
def maxflow(self, graph, s, t):
parent = self.BFS(graph, s, t)
flow = 0
while parent[t] != -1:
flow += self.augmentflow(graph, s, t, parent)
return flow
import numpy as np
class Node(object):
def __init__(self, key, value):
self.key = key
self.value = value
self.marked = False
self.children = []
self.nextSibling = None
self.prevSibling = None
self.parent = None
class FibonacciHeap(object):
def __init__(self):
self.root = None
self.keyDict = {}
def add(self, key, value):
if key in self.keyDict:
return False
if self.root is None:
self.root = Node(key, value)
self.root.nextSibling = self.root
self.root.prevSibling = self
self.keyDict[key] = self.root
return True
node = Node(key, value)
nextsib = self.root.nextSibling
self.root.nextSibling = node
node.nextSibling = nextsib
nextsib.prevSibling = node
node.prevSibling = self.root
if self.root.value > value:
self.root = node
self.keyDict[key] = node
return True
def rebalanceTrees(self):
nodes = []
node = self.root
nodes.insert(len(node.children), node)
node = node.nextSibling
while node != self.root:
index = len(node.children)
smaller_node = node
while (len(nodes) > index)) and (isinstance(nodes[index], Node)):
other_node = nodes[index]
if smaller_node.value > other_node.value:
smaller_node = other_node
other_node = node
smaller_node.children.append(other_node)
other_node.prevSibling = None
other_node.nextSibling = None
other_node.parent = smaller_node
nodes[index] = None
index = len(smaller_node.children)
nodes.insert(index, smaller_node)
min_node = None
prev_node = None
first_node = None
for i in range(len(nodes)):
if nodes[i]:
if min_node is None:
min_node = nodes[i]
elif nodes[i].value < min_node.value:
min_node = nodes[i]
if prev_node:
prev_node.nextSibling = nodes[i]
nodes[i].prevSibling = prev_node
prev_node = nodes[i]
if first_node is None:
first_node = nodes[i]
self.root = min_node
first_node.prevSibling = prev_node
prev_node.nextSibling = first_node
def meldInRootList(self, node, update_root=True):
node.parent = None
nextsib = self.root.nextSibling
self.root.nextSibling = node
node.prevSibling = self.root
node.nextSibling = nextsib
nextsib.prevSibling = node
if update_root:
if self.root.value > node.value:
self.root = node
def pop(self):
if self.root is None:
raise ValueError("Empty heap")
poped_node = self.root
for node in self.root.children:
self.meldInRootList(node, update_root=False)
self.rebalanceTrees()
return popped_node
def update(self, key, new_value):
if key not in self.keyDict:
raise ValueError("Key %s not found in heap"%str(key))
node = self.keyDict[key]
node.value = new_value
if node.parent is not None:
if node.parent.value > new_value:
if not node.parent.marked:
node.parent.marked = True
self.meldInRootList(node)
else:
node.parent.marked = False
self.meldInRootList(node)
self.meldInRootList(node.parent)
else:
if node.value < self.root.value:
self.root = node
import numpy as np
# fod fulkerson algorithm
# graph is adjacency matrix-list using a list of dicts
class Edge(object):
def __init__(self, v, capacity, flow=0):
self.v = v
self.capacity = capacity
self.flow = flow
assert self.flow <= self.capacity
class FordFulkerson(object):
def DFS(self, graph, source, sink, parent):
parent[:] = -1
parent[source] = -2
stack = [source]
while len(stack):
u = stack.pop()
for v in graph[u]:
edge = graph[u][v]
if (parent[v] == -1) and (edge.capacity > edge.flow):
parent[v] = u
stack.append(v)
if v == sink:
return
def augmentflow(self, graph, source, sink, parent):
flow = None
v = sink
if parent[sink] < 0:
return 0
while v != source:
u = parent[v]
edge = graph[u][v]
if (flow is None) or (flow > edge.capacity - edge.flow):
flow = edge.capacity - edge.flow
v = u
if flow is None:
return 0
v = sink
while v != source:
u = parent[v]
edge = graph[u][v]
edge.flow += flow
# reverse edge
if u not in graph[v]:
graph[v] = {u: Edge(u, 0, 0)}
graph[v][u].capacity = edge.flow
return flow
def maxflow(self, graph, source, sink):
self.nVertex = len(graph)
parent = np.ndarray(self.nVertex, dtype=int)
self.DFS(graph, source, sink, parent)
flow = 0
while parent[sink] != -1:
flow += self.augmentflow(graph, source, sink, parent)
self.DFS(graph, source, sink, parent)
return flow
import numpy as np
from collections import deque
class HopcroftKarp(object):
def findLevelGraph(self, uConn, vConn, u_level, u_next, v_next):
u_level[:] = -1
level = -1
queue = deque()
for i in range(len(uConn)):
if u_next[i] == -1:
queue.append(i)
u_level[i] = 0
while len(queue):
u = queue.popleft()
for v in uConn[u]:
if v_next[v] != -1:
un = v_next[v]
if u_level[un] == -1:
queue.append(un)
u_level[un] = u_level[u] + 1
else:
level = u_level[u] + 1
return level
def dfs(self, u, uConn, vConn, u_level, u_next, v_next, level_val):
if u_next[u] != -1:
return False
if u_level[u] < level_val:
return False
for v in uConn[u]:
if v_next[v] == -1:
u_next[u] = v
v_next[v] = u
return True
else:
un = v_next[v]
if u_level[un] == u_level[u] + 1:
found = dfs(un, uConn, vConn, u_level, u_next, v_next, u_level[un])
if found:
u_next[u] = v
v_next[v] = u
return True
return False
def maxflow(self, uConn, vConn):
u_level = np.zeros(len(uConn), dtype=np.int)
u_next = np.zeros(len(uConn), dtype=np.int)
v_next = np.zeros(len(vConn), dtype=np.int)
u_next[:] = -1
v_next[:] = -1
flow =0
while self.findLevelGraph(uConn, vConn, u_level, u_next, v_next):
for u in range(len(uConn)):
if self.DFS(u, uConn, vConn, u_level, v_next, v_next, 0):
flow += 1
return flow
import numpy as np
class KMP(object):
def findLongestPrefix(self):
for i in range(1, len(self.pattern)):
j = i-1
while j >= 0:
last_len = self.lp[j]
if self.pattern[i] == self.pattern[last_len+1]:
self.lp[i] = self.lp[last_len] + 1
break
elif j > 0:
j = self.lp[j]
else:
j = 0 # nt needed as j is 0 here
self.lp[i] = 0
break
def find(self, word):
res = []
if len(word) < len(pattern):
return res
j = 0
i = 0
while i < len(word):
while j >= 0:
if j == len(self.pattern):
res.append(i)
j = self.lp[j]
break
elif word[i] == self.pattern[j]:
j += 1
i += 1
elif j != 0:
j = self.lp[j-1] + 1
else:
i += 1
break
return res
def __init__(self, pattern):
self.pattern = pattern
self.lp = np.zeros(len(pattern), dtype=np.int)
self.findLongestPrefix()
# implement a least recently used eviction cache
class LinkedListNode(object):
def __init__(self, key, val, prev=None, nxt=None):
self.key = key
self.val = val
self.prev = prev
self.nxt = nxt
class LRUCache(object):
def __init__(self, capacity):
self.cache = {}
self.begin = LinkedListNode(None, None)
self.end = LinkedListNode(None, None)
self.begin.next = self.end
self.end.prev = self.begin
self.cap = capacity
def evict(self):
last_nd = self.end.prev
ll_nd = last_nd.prev
self.end.prev = ll_nd
ll_nd.next = self.end
self.cache.pop(last_nd.key) # del self.cache[last_nd.key]
def moveToFront(self, node):
old_next = self.begin.next
nd.prev = self.begin
nd.next = old_next
old_next.prev = nd
def insert(self, key, val):
if key in self.cache:
self.cache[key].val = val
self.moveToFront(self.cache[key])
return
if len(self.cache) == self.capacity:
self.evict()
nd = LinkedListNode(key, val)
self.movetoFront(nd)
self.cache[key] = nd
def get(self, key, default):
if key not in self.cache:
return default
self.moveToFront(self.cache[key])
return self.cache[key].val
import numpy as np
class NQueens(object):
def validateSolution(self, last_row):
for row in range(last_row):
for r2 in range(row+1, last_row):
if self.queenPos[row] == self.queenPos[r2]:
return False
if abs(self.queenPos[r2] - self.queenPos[row]) == r2 - row:
return False
return True
def solutionFromRow(self, row):
if row >= self.n:
return self.validateSolution(self.n)
for col in range(self.n):
self.queenPos[row] = col
if self.validateSolution(row+1):
if self.solutionFromRow(row+1):
return True
return False
def nextSolution(self):
for row in range(self.n):
for col in range(self.n):
self.queenPos[row] = col
if self.validateSolution(row+1):
if self.solutionFromRow(row+1):
return True
return False
def allSoln(self, n):
self.n = n
self.queenPos = np.zeros(n, dtype=int)
solutions = []
while self.nextSolution():
solutions.append(self.queenPos.copy())
return solutions
# Return the number of unique solutions to N queens
class NQueens(object):
def self.recCount(self, board, N, row, usedCols, diag1, diag2):
if row == N:
return 1
count = 0
for j in range(N):
if (j in usedCols) or ((row-j) in diag1) or (row+j) in diag2):
continue
board[row] = j
usedCols.add(j)
diag1.add(row-j)
diag2.add(row+j)
count += self.recCount(board, N, row+1, usedCols, diag1, diag2)
usedCols.remove(j)
diag1.remove(row-j)
diag2.remove(row+j)
return count
def numSoln(self, N):
usedCols = set()
diag1 = {}
diag2 = {}
board = np.zeros(N, dtype=np.int32)
return self.recCount(board, N, 0, usedCols, diag1, diag2)
# count the number of positions in nqueens
class NQueens3(object):
def numPositions(self, blen):
self.boardLen = blen
self.colSet = {}
self.diag1 = {}
self.diag2 = {}
self.solnCount = 0
self.recursiveCount(0)
return self.solnCount
def recursiveCount(self, row):
if row == self.boardLen:
self.solnCount += 1
return
for i in range(self.boardLen):
if i in self.colSet or (row+i) in self.diag1 or (row-i) in self.diag2:
continue
self.colSet.add(i)
self.diag1.add(row+i)
self.diag2.add(row-i)
self.recursiveCount(row+1)
self.colSet.remove(i)
self.diag1.remove((row+i))
self.diag2.remove(row-i)
import numpy as np
class Node(object):
def __init__(self, feature, threshold, left=None, right=None):
self.feature = feature
self.threshold = threshold
self.left = left
self.right = right
class RandomForest(object):
''' Construct a random forest for binary classification problem '''
def __init__(self, ntrees, nsplits=None):
''' Initialize.
:ntrees number of decision trees
:nsplits number of features used to split tree nodes. Tree will have atmost nsplits height
'''
self.trees = [None]*ntrees
self.nSplits = nsplits
self.oobSamples = [None]*ntrees
def _giniNode(self, outputs):
pos = output.sum()
neg = output.shape[0] - pos
prob_pos = pos / float(output.shape[0])
prob_neg = 1 - prob_pos
return prob_pos*(1 - prob_pos) + prob_neg*(1 - prob_neg)
def _getGiniImpRed(self, inputfeature, outputs, threshold):
''' GINI impurity reduction by splitting on feature at threshold '''
gini = self._giniNode(outputs, threshold)
left = (inputfeature < threshold)
right = (inputfeature >= threshold)
gini_left = self._giniNode(outputs[left])
gini_right = self._giniNode(outputs[right])
nobs = outputs.shape[0]
return gini - left.sum()/float(nobs) * gini_left - right.sum()/float(nobs) * gini_right
def _constructTree(self, inputs, outputs, features, splits):
''' Construct a decision tree
:inputs 2 dimensional numpy ndarray of shape (num observations, num features)
:outputs 1 dimensional ndarray with output. Shape (num_observations)
:features list of features to split the node
:splits threshold on number of splits
'''
if splits <= 0:
return
sel_feat = None
reduction = None
sel_threshold = None
for feat in features:
threshold = np.random.choice(inputs[:, feat], size=1)
gini_red = self._getGiniImpRed(inputs[:, feat], outputs, threshold)
if (reduction is None) or (reduction < gini_red):
gini_red = reduction
sel_feat = feat
sel_threshold = threshold
node = Node(sel_feat, sel_threshold)
left_data = (inputs[:, sel_feat] <= sel_threshold)
features_rem = [f for f in features if f != sel_feat]
node.left = self._constructTree(inputs[left_data,:], outputs[left_data], features_rem, splits-1)
right_data = np.logical_not(left_data)
node.right = self._constructTree(inputs[right_data,:], outputs[right_data], features_rem, splits-1)
return node
def construct(self, inputs, outputs):
# assume output is binary
nfeat = inputs.shape[0]
if self.nSplits is None:
self.nSplits = int(np.sqrt(nfeat))
y_labels = sorted(list(set(outputs)))
assert len(y_labels) == 2
y_out = np.where(outputs == y_labels[0], True, False)
features = np.arange(inputs.shape[1])
for i in len(self.trees):
sample_inputs = np.random.choice(inputs.shape[0], inputs.shape[0], replace=True)
self.trees[i] = self.constructTree(inputs[sample_inputs, :], y_out[sample_inputs], features)
self.oobSamples[i] = sample_inputs
import copy
import numpy as np
'''
def nqueen(row):
if row >= N:
return validate(...)
for col in range(N):
self.queenPos[row] = col
precheck
self.nqueen(row+1)
'''
class Soduku(object):
def validateBoard(self, row, col):
used = np.zeros(9, dtype=bool)
for i in range(row+1):
if isinstance(self.board[i][col], str):
val = self.board[i][col] - '0'
else:
val = self.board[i][col]
if used[val]:
return False
used[val] = True
used[:] = False
for j in range(col+1):
val = self.board[row][j]
if isinstance(val, str):
val = val - '0'
if used[val]:
return False
used[val] = True
used[:] = False
if (row%3 == 0) and (col%3 == 0) and (row > 0) and (col > 0):
for i in range(row-2, row+1):
for j in range(col-2, col+1):
val = self.board[i][j]
if isinstance(val, str):
val = val - '0'
if used[val]:
return False
used[val] = True
return True
def findAllSolnsFrom(self, row, col):
if (row, col) == self.board.shape:
if self.validateBoard(row, col):
self.solutions.append(copy.deepcopy(self.board))
else:
return
if self.board[row][col] != '.':
if col < len(self.board)-1:
return self.findAllSolnsFrom(row, col+1)
else:
return self.findAllSolnsFrom(row+1, 0)
else:
for num in range(1, 10):
self.board[row][col] = num
if self.validateBoard(row, col):
if col == self.board.shape[1]-1:
self.findAllSolnsFrom(row+1, 0)
else:
self.findAllSolnsFrom(row, col+1)
def findall(self, board):
if len(board) == 0:
return []
self.solutions = []
self.findAllSolutionsFrom(0,0)
return self.solutions[]
import numpy as np
class TSP(object):
def getSubtour(self, mask, city, tsp, ncities, dist_arr):
if tsp[mask, city] >= 0:
return tsp[mask, city]
min_val = -1.0
for i in range(1, ncities):
if i == city:
continue
if mask & (1 << i):
mask = mask - (1 << i)
val = self.getSubtour(mask, i) + dist_arr[i, city]
if (min_val < 0) or (min_val > val):
min_val = val
mask = mask + (1 << i)
tsp[mask, city] = min_val
return min_val
def shortestTour(self, dist_arr):
# TSP(n, i): shortest tour starting at 0, ending at i, using cities in n mask
# = min(TSP(n-1, k) + dist[k,i] for k in n cities)
ncities = dist_arr.shape[0]
mask_sz = 2**ncities
tsp = np.zeros((mask_sz, ncities), dtype=np.float)
tsp[:,:] = -1
tsp[0,0] = 0
for i in range(1, ncities):
tsp[0, i] = dist_arr[0, i]
min_val = -1
mask = mask_sz - 2
for i in range(1, ncities):
mask = mask - (1 << i)
subtour_dist = self.getSubtour(mask, i, TSP)
if (min_val < 0) or (min_val > subtour_dist + dist_arr[i,0]):
min_val = subtour_dist + dist_arr[i,0]
mask = mask + (1 << i)
return min_val
import numpy as np
class Graph(object):
def __init__(self, nvert):
self.graph = [[]] * nvert #adj list
def addEdge(self, from_vt, to_vt, weight):
self.graph[from_vt].append((to_vt, weight))
class SSSPDag(object):
def __init__(self, graph):
self.graph = graph
def dfs(self, vtx, ordered_vert, indx, visited):
if visited[vtx]:
return indx
visited[vtx] = True
for nbr in self.graph.graph[vtx]:
indx = self.dfs(nbr[0], ordered_vert, indx)
ordered_vert[indx] = vtx
return indx - 1
def topSort(self, ordered_vert):
nvert = len(self.graph.graph)
visited = np.zeros(nvert, dtype=bool)
indx = nvert-1
for i in range(nvert):
indx = self.dfs(i, ordered_vert, indx, visited)
def findSSSP(self, source):
nvert = len(self.graph.graph)
result_dist = np.full(nvert, np.inf, dtype=np.int)
result_dist[source] = 0
ordered_vert = np.zeros(nvert, dtype=np.int)
self.topSort(ordered_vert)
indx = -1
for i in range(nvert):
if ordered_vert[i] == source:
indx = i
break
for i in range(indx, nvert):
vtx = ordered_vert[i]
for nbr in self.graph.graph[vtx]:
if result_dist[nbr[0]] > result_dist[vtx] + nbr[1]:
result_dist[nbr[0]] = result_dist[vtx] + nbr[1]
return result_dist
class Node(object):
def __init__(self, val, left_node=None, right_node=None):
self.value = val
self.leftNode = left_node
self.rightNode = right_node
class RestoreOrder(object):
def inorderTraverse(self, node, last_node, err_node1):
if node.leftNode:
last_node2, err_node1, err_node2 = self.inorderTraverse(node.leftNode, last_node, err_node1)
if err_node2:
return last_node2, err_node1, err_node2
last_node = last_node2
if last_node:
if last_node.value > node.value:
if err_node1:
return last_node, err_node1, node
else:
err_node1 = last_node
last_node = node
if node.rightNode:
last_node2, err_node1, err_node2 = self.inorderTraverse(node.rightNode, last_node, err_node1)
if err_node2:
return last_node2, err_node1, err_node2
last_node = last_node2
return last_node, err_node1, None
def restore(self, tree_root):
if tree_node is None:
raise ValueError("Tree root is None")
last_node, err_node1, err_node2 = self.inorderTraverse(tree_root, None, None)
err_node1.value, err_node2.value = err_node2.value, err_node1.value
return tree_root
from collections import deque
class Node(object):
def __init__(self, val, left=None, right=None):
self.value = val
self.left == left
self.right = right
def Serialize(object):
def serialize(self, root):
if root is None:
return ""
queue = deque()
vals = []
queue.append(root)
while len(queue):
node = queue.popleft()
if node is None:
vals.append("None")
else:
vals.append(node.value)
queue.append(node.left)
queue.append(node.right)
return " ".join(vals)
def desialize(self, ser_str):
parts = ser_str.split()
if len(parts) == 0:
return None
if parts[0] == "None":
return None
root = Node(float(parts[0]))
index = 1
queue = deque()
queue.append((root, "left"))
queue.append((root, "right"))