Add Python doctests to count-inversions.py (#159)

* Add Python doctests to count-inversions.py

These [doctests](https://docs.python.org/3/library/doctest.html) can be run with `python3 -m doctest -v count-inversions.py`

Our GitHub Actions will also run these doctests.  https://github.com/MakeContributions/DSA/actions

The answer to the last test should be 0, not 2.

@atin Your review please.

* Avoid unnecessary inversions
pull/173/head
Christian Clauss 2021-04-12 12:03:47 +02:00 committed by GitHub
parent e151d71572
commit 2a8185f159
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 20 additions and 5 deletions

View File

@ -2,6 +2,8 @@
Algorithm Type: Divide & Conquer Algorithm Type: Divide & Conquer
Time Complexity: O(n*log(n)) Time Complexity: O(n*log(n))
""" """
numbers = [8, 2, 1, 5, 7, 3, 9, 2, 0, 1]
def count_split_inv(arr, left, right): def count_split_inv(arr, left, right):
split_inv = ridx = lidx = 0 split_inv = ridx = lidx = 0
@ -10,7 +12,7 @@ def count_split_inv(arr, left, right):
rsize = len(right) rsize = len(right)
for i in range(size): for i in range(size):
if lidx != lsize and ridx != rsize: if lidx != lsize and ridx != rsize:
if right[ridx] <= left[lidx]: if right[ridx] < left[lidx]:
arr[i] = right[ridx] arr[i] = right[ridx]
ridx += 1 ridx += 1
split_inv += lsize - lidx split_inv += lsize - lidx
@ -23,9 +25,22 @@ def count_split_inv(arr, left, right):
elif ridx == rsize: elif ridx == rsize:
arr[i] = left[lidx] arr[i] = left[lidx]
lidx += 1 lidx += 1
return split_inv; return split_inv
def count_inversions(arr):
def count_inversions(arr) -> int:
"""
Sort arr and return the number of inversions required.
>>> numbers
[8, 2, 1, 5, 7, 3, 9, 2, 0, 1]
>>> count_inversions(numbers)
28
>>> numbers # numbers has been sorted!!
[0, 1, 1, 2, 2, 3, 5, 7, 8, 9]
>>> count_inversions(numbers)
0
"""
size = len(arr) size = len(arr)
if size == 1: if size == 1:
return 0 return 0
@ -38,5 +53,5 @@ def count_inversions(arr):
return l_inv + r_inv + split_inv return l_inv + r_inv + split_inv
numbers = [8, 2, 1, 5, 7, 3, 9, 2, 0, 1] if __name__ == "__main__":
print(count_inversions(numbers)) print(count_inversions(numbers))