Skip to content

Instantly share code, notes, and snippets.

@willy-r
Created November 21, 2020 00:51
Show Gist options
  • Save willy-r/f4ca2b2b8f63e55b668ae0543e1910e0 to your computer and use it in GitHub Desktop.
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.
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