-
Notifications
You must be signed in to change notification settings - Fork 0
/
dutch_national_flag.py
55 lines (45 loc) · 1.46 KB
/
dutch_national_flag.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
import functools
from test_framework import generic_test
from test_framework.test_failure import TestFailure
from test_framework.test_utils import enable_executor_hook
def dutch_flag_partition(pivot_index, A):
pivot = A[pivot_index]
low = 0
mid = 0
high = len(A) - 1
while mid <= high:
if A[mid] < pivot:
A[mid], A[low] = A[low], A[mid]
low += 1
mid += 1
elif A[mid] == pivot:
mid += 1
elif A[mid] > pivot:
A[mid], A[high] = A[high], A[mid]
high -= 1
@enable_executor_hook
def dutch_flag_partition_wrapper(executor, A, pivot_idx):
count = [0, 0, 0]
for x in A:
count[x] += 1
pivot = A[pivot_idx]
executor.run(functools.partial(dutch_flag_partition, pivot_idx, A))
i = 0
while i < len(A) and A[i] < pivot:
count[A[i]] -= 1
i += 1
while i < len(A) and A[i] == pivot:
count[A[i]] -= 1
i += 1
while i < len(A) and A[i] > pivot:
count[A[i]] -= 1
i += 1
if i != len(A):
raise TestFailure('Not partitioned after {}th element'.format(i))
elif any(count):
raise TestFailure("Some elements are missing from original array")
if __name__ == '__main__':
exit(
generic_test.generic_test_main("dutch_national_flag.py",
'dutch_national_flag.tsv',
dutch_flag_partition_wrapper))