-
Notifications
You must be signed in to change notification settings - Fork 313
/
Copy pathalgorithms.py
2012 lines (1696 loc) · 56.8 KB
/
algorithms.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
from pydatastructs.linear_data_structures.arrays import (
OneDimensionalArray, DynamicArray, DynamicOneDimensionalArray, Array)
from pydatastructs.linear_data_structures._backend.cpp import _algorithms, _arrays
from pydatastructs.utils.misc_util import (
_check_type, _comp, Backend,
raise_if_backend_is_not_python)
from concurrent.futures import ThreadPoolExecutor
from math import log, floor, sqrt
__all__ = [
'merge_sort_parallel',
'brick_sort',
'brick_sort_parallel',
'heapsort',
'matrix_multiply_parallel',
'counting_sort',
'bucket_sort',
'cocktail_shaker_sort',
'quick_sort',
'longest_common_subsequence',
'is_ordered',
'upper_bound',
'lower_bound',
'longest_increasing_subsequence',
'next_permutation',
'prev_permutation',
'bubble_sort',
'linear_search',
'binary_search',
'jump_search',
'selection_sort',
'insertion_sort',
'intro_sort',
'shell_sort',
'radix_sort'
]
def _merge(array, sl, el, sr, er, end, comp):
l, r = [], []
for i in range(sl, el + 1):
if i <= end:
l.append(array[i])
array[i] = None
for i in range(sr, er + 1):
if i <= end:
r.append(array[i])
array[i] = None
i, j, k = 0, 0, sl
while i < len(l) and j < len(r):
if _comp(l[i], r[j], comp):
array[k] = l[i]
i += 1
else:
array[k] = r[j]
j += 1
k += 1
while i < len(l):
array[k] = l[i]
i += 1
k += 1
while j < len(r):
array[k] = r[j]
j += 1
k += 1
def merge_sort_parallel(array, num_threads, **kwargs):
"""
Implements parallel merge sort.
Parameters
==========
array: Array
The array which is to be sorted.
num_threads: int
The maximum number of threads
to be used for sorting.
start: int
The starting index of the portion
which is to be sorted.
Optional, by default 0
end: int
The ending index of the portion which
is to be sorted.
Optional, by default the index
of the last position filled.
comp: lambda/function
The comparator which is to be used
for sorting. If the function returns
False then only swapping is performed.
Optional, by default, less than or
equal to is used for comparing two
values.
backend: pydatastructs.Backend
The backend to be used.
Optional, by default, the best available
backend is used.
Examples
========
>>> from pydatastructs import OneDimensionalArray, merge_sort_parallel
>>> arr = OneDimensionalArray(int,[3, 2, 1])
>>> merge_sort_parallel(arr, 3)
>>> [arr[0], arr[1], arr[2]]
[1, 2, 3]
>>> merge_sort_parallel(arr, 3, comp=lambda u, v: u > v)
>>> [arr[0], arr[1], arr[2]]
[3, 2, 1]
References
==========
.. [1] https://en.wikipedia.org/wiki/Merge_sort
"""
raise_if_backend_is_not_python(
merge_sort_parallel, kwargs.get('backend', Backend.PYTHON))
start = kwargs.get('start', 0)
end = kwargs.get('end', len(array) - 1)
comp = kwargs.get("comp", lambda u, v: u <= v)
for size in range(floor(log(end - start + 1, 2)) + 1):
pow_2 = 2**size
with ThreadPoolExecutor(max_workers=num_threads) as Executor:
i = start
while i <= end:
Executor.submit(
_merge,
array,
i, i + pow_2 - 1,
i + pow_2, i + 2*pow_2 - 1,
end, comp).result()
i = i + 2*pow_2
if _check_type(array, (DynamicArray, _arrays.DynamicOneDimensionalArray)):
array._modify(True)
def brick_sort(array, **kwargs):
"""
Implements Brick Sort / Odd Even sorting algorithm
Parameters
==========
array: Array
The array which is to be sorted.
start: int
The starting index of the portion
which is to be sorted.
Optional, by default 0
end: int
The ending index of the portion which
is to be sorted.
Optional, by default the index
of the last position filled.
comp: lambda/function
The comparator which is to be used
for sorting. If the function returns
False then only swapping is performed.
Optional, by default, less than or
equal to is used for comparing two
values.
backend: pydatastructs.Backend
The backend to be used.
Optional, by default, the best available
backend is used.
Examples
========
>>> from pydatastructs import OneDimensionalArray, brick_sort
>>> arr = OneDimensionalArray(int,[3, 2, 1])
>>> brick_sort(arr)
>>> [arr[0], arr[1], arr[2]]
[1, 2, 3]
>>> brick_sort(arr, comp=lambda u, v: u > v)
>>> [arr[0], arr[1], arr[2]]
[3, 2, 1]
References
==========
.. [1] https://www.geeksforgeeks.org/odd-even-sort-brick-sort/
"""
raise_if_backend_is_not_python(
brick_sort, kwargs.get('backend', Backend.PYTHON))
start = kwargs.get('start', 0)
end = kwargs.get('end', len(array) - 1)
comp = kwargs.get("comp", lambda u, v: u <= v)
is_sorted = False
while is_sorted is False:
is_sorted = True
for i in range(start+1, end, 2):
if _comp(array[i+1], array[i], comp):
array[i], array[i+1] = array[i+1], array[i]
is_sorted = False
for i in range(start, end, 2):
if _comp(array[i+1], array[i], comp):
array[i], array[i+1] = array[i+1], array[i]
is_sorted = False
if _check_type(array, (DynamicArray, _arrays.DynamicOneDimensionalArray)):
array._modify(True)
def _brick_sort_swap(array, i, j, comp, is_sorted):
if _comp(array[j], array[i], comp):
array[i], array[j] = array[j], array[i]
is_sorted[0] = False
def brick_sort_parallel(array, num_threads, **kwargs):
"""
Implements Concurrent Brick Sort / Odd Even sorting algorithm
Parameters
==========
array: Array/list
The array which is to be sorted.
num_threads: int
The maximum number of threads
to be used for sorting.
start: int
The starting index of the portion
which is to be sorted.
Optional, by default 0
end: int
The ending index of the portion which
is to be sorted.
Optional, by default the index
of the last position filled.
comp: lambda/function
The comparator which is to be used
for sorting. If the function returns
False then only swapping is performed.
Optional, by default, less than or
equal to is used for comparing two
values.
backend: pydatastructs.Backend
The backend to be used.
Optional, by default, the best available
backend is used.
Examples
========
>>> from pydatastructs import OneDimensionalArray, brick_sort_parallel
>>> arr = OneDimensionalArray(int,[3, 2, 1])
>>> brick_sort_parallel(arr, num_threads=5)
>>> [arr[0], arr[1], arr[2]]
[1, 2, 3]
>>> brick_sort_parallel(arr, num_threads=5, comp=lambda u, v: u > v)
>>> [arr[0], arr[1], arr[2]]
[3, 2, 1]
References
==========
.. [1] https://en.wikipedia.org/wiki/Odd%E2%80%93even_sort
"""
raise_if_backend_is_not_python(
brick_sort_parallel, kwargs.get('backend', Backend.PYTHON))
start = kwargs.get('start', 0)
end = kwargs.get('end', len(array) - 1)
comp = kwargs.get("comp", lambda u, v: u <= v)
is_sorted = [False]
with ThreadPoolExecutor(max_workers=num_threads) as Executor:
while is_sorted[0] is False:
is_sorted[0] = True
for i in range(start + 1, end, 2):
Executor.submit(_brick_sort_swap, array, i, i + 1, comp, is_sorted).result()
for i in range(start, end, 2):
Executor.submit(_brick_sort_swap, array, i, i + 1, comp, is_sorted).result()
if _check_type(array, (DynamicArray, _arrays.DynamicOneDimensionalArray)):
array._modify(True)
def heapsort(array, **kwargs):
"""
Implements Heapsort algorithm.
Parameters
==========
array: Array
The array which is to be sorted.
start: int
The starting index of the portion
which is to be sorted.
Optional, by default 0
end: int
The ending index of the portion which
is to be sorted.
Optional, by default the index
of the last position filled.
backend: pydatastructs.Backend
The backend to be used.
Optional, by default, the best available
backend is used.
Examples
========
>>> from pydatastructs import OneDimensionalArray, heapsort
>>> arr = OneDimensionalArray(int,[3, 2, 1])
>>> heapsort(arr)
>>> [arr[0], arr[1], arr[2]]
[1, 2, 3]
References
==========
.. [1] https://en.wikipedia.org/wiki/Heapsort
Note
====
This function does not support custom comparators as is the case with
other sorting functions in this file.
"""
raise_if_backend_is_not_python(
heapsort, kwargs.get('backend', Backend.PYTHON))
from pydatastructs.trees.heaps import BinaryHeap
start = kwargs.get('start', 0)
end = kwargs.get('end', len(array) - 1)
h = BinaryHeap(heap_property="min")
for i in range(start, end+1):
if array[i] is not None:
h.insert(array[i])
array[i] = None
i = start
while not h.is_empty:
array[i] = h.extract().key
i += 1
if _check_type(array, (DynamicArray, _arrays.DynamicOneDimensionalArray)):
array._modify(True)
def counting_sort(array: Array, **kwargs) -> Array:
"""
Performs counting sort on the given array.
Parameters
==========
array: Array
The array which is to be sorted.
backend: pydatastructs.Backend
The backend to be used.
Optional, by default, the best available
backend is used.
Returns
=======
output: Array
The sorted array.
Examples
========
>>> from pydatastructs import DynamicOneDimensionalArray as DODA, counting_sort
>>> arr = DODA(int, [5, 78, 1, 0])
>>> out = counting_sort(arr)
>>> str(out)
"['0', '1', '5', '78']"
>>> arr.delete(2)
>>> out = counting_sort(arr)
>>> str(out)
"['0', '5', '78']"
References
==========
.. [1] https://en.wikipedia.org/wiki/Counting_sort
Note
====
Since, counting sort is a non-comparison sorting algorithm,
custom comparators aren't allowed.
The ouput array doesn't contain any `None` value.
"""
raise_if_backend_is_not_python(
counting_sort, kwargs.get('backend', Backend.PYTHON))
max_val, min_val = array[0], array[0]
none_count = 0
for i in range(len(array)):
if array[i] is not None:
if max_val is None or max_val < array[i]:
max_val = array[i]
if min_val is None or array[i] < min_val:
min_val = array[i]
else:
none_count += 1
if min_val is None or max_val is None:
return array
count = [0 for _ in range(max_val - min_val + 1)]
for i in range(len(array)):
if array[i] is not None:
count[array[i] - min_val] += 1
total = 0
for i in range(max_val - min_val + 1):
count[i], total = total, count[i] + total
output = type(array)(array._dtype,
[array[i] for i in range(len(array))
if array[i] is not None])
if _check_type(output, DynamicArray):
output._modify(force=True)
for i in range(len(array)):
x = array[i]
if x is not None:
output[count[x-min_val]] = x
count[x-min_val] += 1
return output
def _matrix_multiply_helper(m1, m2, row, col):
s = 0
for i in range(len(m1)):
s += m1[row][i] * m2[i][col]
return s
def matrix_multiply_parallel(matrix_1, matrix_2, num_threads):
"""
Implements concurrent Matrix multiplication
Parameters
==========
matrix_1: Any matrix representation
Left matrix
matrix_2: Any matrix representation
Right matrix
num_threads: int
The maximum number of threads
to be used for multiplication.
backend: pydatastructs.Backend
The backend to be used.
Optional, by default, the best available
backend is used.
Raises
======
ValueError
When the columns in matrix_1 are not equal to the rows in matrix_2
Returns
=======
C: list
The result of matrix multiplication.
Examples
========
>>> from pydatastructs import matrix_multiply_parallel
>>> I = [[1, 1, 0], [0, 1, 0], [0, 0, 1]]
>>> J = [[2, 1, 2], [1, 2, 1], [2, 2, 2]]
>>> matrix_multiply_parallel(I, J, num_threads=5)
[[3, 3, 3], [1, 2, 1], [2, 2, 2]]
References
==========
.. [1] https://www3.nd.edu/~zxu2/acms60212-40212/Lec-07-3.pdf
"""
row_matrix_1, col_matrix_1 = len(matrix_1), len(matrix_1[0])
row_matrix_2, col_matrix_2 = len(matrix_2), len(matrix_2[0])
if col_matrix_1 != row_matrix_2:
raise ValueError("Matrix size mismatch: %s * %s"%(
(row_matrix_1, col_matrix_1), (row_matrix_2, col_matrix_2)))
C = [[None for i in range(col_matrix_1)] for j in range(row_matrix_2)]
with ThreadPoolExecutor(max_workers=num_threads) as Executor:
for i in range(row_matrix_1):
for j in range(col_matrix_2):
C[i][j] = Executor.submit(_matrix_multiply_helper,
matrix_1,
matrix_2,
i, j).result()
return C
def _bucket_sort_helper(bucket: Array) -> Array:
for i in range(1, len(bucket)):
key = bucket[i]
j = i - 1
while j >= 0 and bucket[j] > key:
bucket[j+1] = bucket[j]
j -= 1
bucket[j+1] = key
return bucket
def bucket_sort(array: Array, **kwargs) -> Array:
"""
Performs bucket sort on the given array.
Parameters
==========
array: Array
The array which is to be sorted.
start: int
The starting index of the portion
which is to be sorted.
Optional, by default 0
end: int
The ending index of the portion which
is to be sorted.
Optional, by default the index
of the last position filled.
backend: pydatastructs.Backend
The backend to be used.
Optional, by default, the best available
backend is used.
Returns
=======
output: Array
The sorted array.
Examples
========
>>> from pydatastructs import DynamicOneDimensionalArray as DODA, bucket_sort
>>> arr = DODA(int, [5, 78, 1, 0])
>>> out = bucket_sort(arr)
>>> str(out)
"['0', '1', '5', '78']"
>>> arr.delete(2)
>>> out = bucket_sort(arr)
>>> str(out)
"['0', '1', '78']"
References
==========
.. [1] https://en.wikipedia.org/wiki/Bucket_sort
Note
====
This function does not support custom comparators as is the case with
other sorting functions in this file.
"""
raise_if_backend_is_not_python(
bucket_sort, kwargs.get('backend', Backend.PYTHON))
start = kwargs.get('start', 0)
end = kwargs.get('end', len(array) - 1)
#Find maximum value in the list and use length of the list to determine which value in the list goes into which bucket
max_value = None
for i in range(start, end+1):
if array[i] is not None:
max_value = array[i]
count = 0
for i in range(start, end+1):
if array[i] is not None:
count += 1
if array[i] > max_value:
max_value = array[i]
number_of_null_values = end - start + 1 - count
size = max_value // count
# Create n empty buckets where n is equal to the length of the input list
buckets_list = [[] for _ in range(count)]
# Put list elements into different buckets based on the size
for i in range(start, end + 1):
if array[i] is not None:
j = array[i] // size
if j is not count:
buckets_list[j].append(array[i])
else:
buckets_list[count-1].append(array[i])
# Sort elements within the buckets using Insertion Sort
for z in range(count):
_bucket_sort_helper(buckets_list[z])
# Concatenate buckets with sorted elements into a single array
sorted_list = []
for x in range(count):
sorted_list.extend(buckets_list[x])
for i in range(end, end - number_of_null_values, -1):
array[i] = None
for i in range(start, end - number_of_null_values + 1):
array[i] = sorted_list[i-start]
if _check_type(array, (DynamicArray, _arrays.DynamicOneDimensionalArray)):
array._modify(True)
return array
def cocktail_shaker_sort(array: Array, **kwargs) -> Array:
"""
Performs cocktail sort on the given array.
Parameters
==========
array: Array
The array which is to be sorted.
start: int
The starting index of the portion
which is to be sorted.
Optional, by default 0
end: int
The ending index of the portion which
is to be sorted.
Optional, by default the index
of the last position filled.
comp: lambda/function
The comparator which is to be used
for sorting. If the function returns
False then only swapping is performed.
Optional, by default, less than or
equal to is used for comparing two
values.
backend: pydatastructs.Backend
The backend to be used.
Optional, by default, the best available
backend is used.
Returns
=======
output: Array
The sorted array.
Examples
========
>>> from pydatastructs import OneDimensionalArray as ODA, cocktail_shaker_sort
>>> arr = ODA(int, [5, 78, 1, 0])
>>> out = cocktail_shaker_sort(arr)
>>> str(out)
'[0, 1, 5, 78]'
>>> arr = ODA(int, [21, 37, 5])
>>> out = cocktail_shaker_sort(arr)
>>> str(out)
'[5, 21, 37]'
References
==========
.. [1] https://en.wikipedia.org/wiki/Cocktail_shaker_sort
"""
backend = kwargs.pop("backend", Backend.PYTHON)
if backend == Backend.CPP:
return _algorithms.cocktail_shaker_sort(array, **kwargs)
raise_if_backend_is_not_python(
cocktail_shaker_sort, kwargs.get('backend', Backend.PYTHON))
def swap(i, j):
array[i], array[j] = array[j], array[i]
lower = kwargs.get('start', 0)
upper = kwargs.get('end', len(array) - 1)
comp = kwargs.get("comp", lambda u, v: u <= v)
swapping = False
while (not swapping and upper - lower >= 1):
swapping = True
for j in range(lower, upper):
if _comp(array[j], array[j+1], comp) is False:
swap(j + 1, j)
swapping = False
upper = upper - 1
for j in range(upper, lower, -1):
if _comp(array[j-1], array[j], comp) is False:
swap(j, j - 1)
swapping = False
lower = lower + 1
if _check_type(array, (DynamicArray, _arrays.DynamicOneDimensionalArray)):
array._modify(True)
return array
def quick_sort(array: Array, **kwargs) -> Array:
"""
Performs quick sort on the given array.
Parameters
==========
array: Array
The array which is to be sorted.
start: int
The starting index of the portion
which is to be sorted.
Optional, by default 0
end: int
The ending index of the portion which
is to be sorted.
Optional, by default the index
of the last position filled.
comp: lambda/function
The comparator which is to be used
for sorting. If the function returns
False then only swapping is performed.
Optional, by default, less than or
equal to is used for comparing two
values.
pick_pivot_element: lambda/function
The function implementing the pivot picking
logic for quick sort. Should accept, `low`,
`high`, and `array` in this order, where `low`
represents the left end of the current partition,
`high` represents the right end, and `array` is
the original input array to `quick_sort` function.
Optional, by default, picks the element at `high`
index of the current partition as pivot.
backend: pydatastructs.Backend
The backend to be used.
Optional, by default, the best available
backend is used.
Returns
=======
output: Array
The sorted array.
Examples
========
>>> from pydatastructs import OneDimensionalArray as ODA, quick_sort
>>> arr = ODA(int, [5, 78, 1, 0])
>>> out = quick_sort(arr)
>>> str(out)
'[0, 1, 5, 78]'
>>> arr = ODA(int, [21, 37, 5])
>>> out = quick_sort(arr)
>>> str(out)
'[5, 21, 37]'
References
==========
.. [1] https://en.wikipedia.org/wiki/Quicksort
"""
backend = kwargs.pop("backend", Backend.PYTHON)
if backend == Backend.CPP:
return _algorithms.quick_sort(array, **kwargs)
from pydatastructs import Stack
comp = kwargs.get("comp", lambda u, v: u <= v)
pick_pivot_element = kwargs.get("pick_pivot_element",
lambda low, high, array: array[high])
def partition(low, high, pick_pivot_element):
i = (low - 1)
x = pick_pivot_element(low, high, array)
for j in range(low , high):
if _comp(array[j], x, comp) is True:
i = i + 1
array[i], array[j] = array[j], array[i]
array[i + 1], array[high] = array[high], array[i + 1]
return (i + 1)
lower = kwargs.get('start', 0)
upper = kwargs.get('end', len(array) - 1)
stack = Stack()
stack.push(lower)
stack.push(upper)
while stack.is_empty is False:
high = stack.pop()
low = stack.pop()
p = partition(low, high, pick_pivot_element)
if p - 1 > low:
stack.push(low)
stack.push(p - 1)
if p + 1 < high:
stack.push(p + 1)
stack.push(high)
if _check_type(array, (DynamicArray, _arrays.DynamicOneDimensionalArray)):
array._modify(True)
return array
def longest_common_subsequence(seq1: OneDimensionalArray, seq2: OneDimensionalArray,
**kwargs) -> OneDimensionalArray:
"""
Finds the longest common subsequence between the
two given sequences.
Parameters
========
seq1: OneDimensionalArray
The first sequence.
seq2: OneDimensionalArray
The second sequence.
backend: pydatastructs.Backend
The backend to be used.
Optional, by default, the best available
backend is used.
Returns
=======
output: OneDimensionalArray
The longest common subsequence.
Examples
========
>>> from pydatastructs import longest_common_subsequence as LCS, OneDimensionalArray as ODA
>>> arr1 = ODA(str, ['A', 'B', 'C', 'D', 'E'])
>>> arr2 = ODA(str, ['A', 'B', 'C', 'G' ,'D', 'E', 'F'])
>>> lcs = LCS(arr1, arr2)
>>> str(lcs)
"['A', 'B', 'C', 'D', 'E']"
>>> arr1 = ODA(str, ['A', 'P', 'P'])
>>> arr2 = ODA(str, ['A', 'p', 'P', 'S', 'P'])
>>> lcs = LCS(arr1, arr2)
>>> str(lcs)
"['A', 'P', 'P']"
References
==========
.. [1] https://en.wikipedia.org/wiki/Longest_common_subsequence_problem
Note
====
The data types of elements across both the sequences
should be same and should be comparable.
"""
raise_if_backend_is_not_python(
longest_common_subsequence, kwargs.get('backend', Backend.PYTHON))
row = len(seq1)
col = len(seq2)
check_mat = {0: [(0, []) for _ in range(col + 1)]}
for i in range(1, row + 1):
check_mat[i] = [(0, []) for _ in range(col + 1)]
for j in range(1, col + 1):
if seq1[i-1] == seq2[j-1]:
temp = check_mat[i-1][j-1][1][:]
temp.append(seq1[i-1])
check_mat[i][j] = (check_mat[i-1][j-1][0] + 1, temp)
else:
if check_mat[i-1][j][0] > check_mat[i][j-1][0]:
check_mat[i][j] = check_mat[i-1][j]
else:
check_mat[i][j] = check_mat[i][j-1]
return OneDimensionalArray(seq1._dtype, check_mat[row][col][-1])
def is_ordered(array, **kwargs):
"""
Checks whether the given array is ordered or not.
Parameters
==========
array: OneDimensionalArray
The array which is to be checked for having
specified ordering among its elements.
start: int
The starting index of the portion of the array
under consideration.
Optional, by default 0
end: int
The ending index of the portion of the array
under consideration.
Optional, by default the index
of the last position filled.
comp: lambda/function
The comparator which is to be used
for specifying the desired ordering.
Optional, by default, less than or
equal to is used for comparing two
values.
backend: pydatastructs.Backend
The backend to be used.
Optional, by default, the best available
backend is used.
Returns
=======
True if the specified ordering is present
from start to end (inclusive) otherwise False.
Examples
========
>>> from pydatastructs import OneDimensionalArray, is_ordered
>>> arr = OneDimensionalArray(int, [1, 2, 3, 4])
>>> is_ordered(arr)
True
>>> arr1 = OneDimensionalArray(int, [1, 2, 3])
>>> is_ordered(arr1, start=0, end=1, comp=lambda u, v: u > v)
False
"""
backend = kwargs.pop("backend", Backend.PYTHON)
if backend == Backend.CPP:
return _algorithms.is_ordered(array, **kwargs)
lower = kwargs.get('start', 0)
upper = kwargs.get('end', len(array) - 1)
comp = kwargs.get("comp", lambda u, v: u <= v)
for i in range(lower + 1, upper + 1):
if array[i] is None or array[i - 1] is None:
continue
if comp(array[i], array[i - 1]):
return False
return True
def upper_bound(array, value, **kwargs):
"""
Finds the index of the first occurence of an element greater than the given
value according to specified order, in the given OneDimensionalArray using a variation of binary search method.
Parameters
==========
array: OneDimensionalArray
The array in which the upper bound has to be found.
start: int
The staring index of the portion of the array in which the upper bound
of a given value has to be looked for.
Optional, by default 0
end: int, optional
The ending index of the portion of the array in which the upper bound
of a given value has to be looked for.
Optional, by default the index
of the last position filled.
comp: lambda/function
The comparator which is to be used
for specifying the desired ordering.
Optional, by default, less than or
equal to is used for comparing two
values.
backend: pydatastructs.Backend
The backend to be used.
Optional, by default, the best available
backend is used.
Returns
=======
index: int
Index of the upper bound of the given value in the given OneDimensionalArray.
Examples
========
>>> from pydatastructs import upper_bound, OneDimensionalArray as ODA
>>> arr1 = ODA(int, [4, 5, 5, 6, 7])
>>> ub = upper_bound(arr1, 5, start=0, end=4)
>>> ub
3
>>> arr2 = ODA(int, [7, 6, 5, 5, 4])
>>> ub = upper_bound(arr2, 5, comp=lambda x, y: x > y)
>>> ub
4
Note
====
DynamicOneDimensionalArray objects may not work as expected.
"""
raise_if_backend_is_not_python(
upper_bound, kwargs.get('backend', Backend.PYTHON))
start = kwargs.get('start', 0)
end = kwargs.get('end', len(array))
comp = kwargs.get('comp', lambda x, y: x < y)
index = end
inclusive_end = end - 1
if comp(value, array[start]):
index = start
while start <= inclusive_end:
mid = (start + inclusive_end)//2
if not comp(value, array[mid]):
start = mid + 1
else:
index = mid
inclusive_end = mid - 1