mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-12-18 01:00:15 +00:00
bc8df6de31
* [pre-commit.ci] pre-commit autoupdate updates: - [github.com/astral-sh/ruff-pre-commit: v0.2.2 → v0.3.2](https://github.com/astral-sh/ruff-pre-commit/compare/v0.2.2...v0.3.2) - [github.com/pre-commit/mirrors-mypy: v1.8.0 → v1.9.0](https://github.com/pre-commit/mirrors-mypy/compare/v1.8.0...v1.9.0) * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
30 lines
702 B
Python
30 lines
702 B
Python
#!/usr/bin/env python3
|
|
|
|
"""
|
|
Given an array of integers and an integer req_sum, find the number of pairs of array
|
|
elements whose sum is equal to req_sum.
|
|
|
|
https://practice.geeksforgeeks.org/problems/count-pairs-with-given-sum5022/0
|
|
"""
|
|
|
|
from itertools import combinations
|
|
|
|
|
|
def pairs_with_sum(arr: list, req_sum: int) -> int:
|
|
"""
|
|
Return the no. of pairs with sum "sum"
|
|
>>> pairs_with_sum([1, 5, 7, 1], 6)
|
|
2
|
|
>>> pairs_with_sum([1, 1, 1, 1, 1, 1, 1, 1], 2)
|
|
28
|
|
>>> pairs_with_sum([1, 7, 6, 2, 5, 4, 3, 1, 9, 8], 7)
|
|
4
|
|
"""
|
|
return len([1 for a, b in combinations(arr, 2) if a + b == req_sum])
|
|
|
|
|
|
if __name__ == "__main__":
|
|
from doctest import testmod
|
|
|
|
testmod()
|