From 2a8185f159222a31fb66baa220bc6f0c321444b3 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Mon, 12 Apr 2021 12:03:47 +0200 Subject: [PATCH] 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 --- arrays/python/count-inversions.py | 25 ++++++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/arrays/python/count-inversions.py b/arrays/python/count-inversions.py index 16190435..2bbbc5bd 100644 --- a/arrays/python/count-inversions.py +++ b/arrays/python/count-inversions.py @@ -2,6 +2,8 @@ Algorithm Type: Divide & Conquer Time Complexity: O(n*log(n)) """ +numbers = [8, 2, 1, 5, 7, 3, 9, 2, 0, 1] + def count_split_inv(arr, left, right): split_inv = ridx = lidx = 0 @@ -10,7 +12,7 @@ def count_split_inv(arr, left, right): rsize = len(right) for i in range(size): if lidx != lsize and ridx != rsize: - if right[ridx] <= left[lidx]: + if right[ridx] < left[lidx]: arr[i] = right[ridx] ridx += 1 split_inv += lsize - lidx @@ -23,9 +25,22 @@ def count_split_inv(arr, left, right): elif ridx == rsize: arr[i] = left[lidx] 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) if size == 1: return 0 @@ -38,5 +53,5 @@ def count_inversions(arr): return l_inv + r_inv + split_inv -numbers = [8, 2, 1, 5, 7, 3, 9, 2, 0, 1] -print(count_inversions(numbers)) +if __name__ == "__main__": + print(count_inversions(numbers))