Created
December 1, 2020 18:16
-
-
Save willy-r/a348f3fce9ea48d17c1615ee60e14600 to your computer and use it in GitHub Desktop.
Given an array of integers and a target value, return the number of pairs of array elements that have a difference equal to a target value.
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 array_diff(arr: list[int], n: int) -> int: | |
count = 0 | |
for i in range(len(arr)): | |
for j in range(i + 1, len(arr)): | |
if arr[i] - arr[j] == n or arr[j] - arr[i] == n: | |
count += 1 | |
return count | |
def test_example(): | |
assert array_diff([1, 2, 3, 4], 1) == 3 | |
def test_positive_values(): | |
assert array_diff([2, 4, 6, 8, 10], 2) == 4 | |
def test_negative_values(): | |
assert array_diff([-1, -2, -3, -4], -1) == 3 | |
def test_target_zero_with_duplicates(): | |
assert array_diff([1, 1, 2, 3, 3, 4], 0) == 2 | |
def test_negative_target(): | |
assert array_diff([5, 1, 3, 4, 2], -1) == 4 | |
if __name__ == '__main__': | |
test_example() | |
test_positive_values() | |
test_negative_values() | |
test_target_zero_with_duplicates() | |
test_negative_target() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment