Created
November 21, 2020 00:51
-
-
Save willy-r/f4ca2b2b8f63e55b668ae0543e1910e0 to your computer and use it in GitHub Desktop.
Given an array of integers arr, a pair (n,m) is called “special” if arr[n] == arr[m], and n < m. Return the number of special pairs.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def is_spair(arr: list[int], n: int, m: int) -> bool: | |
return arr[n] == arr[m] and n < m | |
def special_pairs_list_comprehension(arr: list[int]) -> int: | |
return len( | |
[(arr[i], arr[j]) | |
for i in range(len(arr)) | |
for j in range(i + 1, len(arr)) | |
if is_spair(arr, i, j)] | |
) | |
def special_pairs(arr: list[int], v: bool = False) -> int: | |
count = 0 | |
pairs = [] | |
for i in range(len(arr)): | |
for j in range(i + 1, len(arr)): | |
if is_spair(arr, i, j): | |
pairs.append((i, j)) | |
count += 1 | |
if v: | |
print(pairs) | |
return count | |
if __name__ == '__main__': | |
CASES = ( | |
([1, 2, 3, 1, 1, 3], 4), | |
([5, 6, 7, 5, 6, 7], 3), | |
([1, 2, 3, 4, 5, 6], 0), | |
([1, 2, 2, 2, 2, 1], 7), | |
([200, 100, 100, 200], 2), | |
([1], 0), | |
([1, 1], 1), | |
) | |
for arr_test, expected in CASES: | |
result = special_pairs(arr_test, True) | |
assert result == expected, f'{result=} != {expected=}' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment