Skip to content

Commit 09ce6b2

Browse files
siddwarrpre-commit-ci[bot]cclauss
authored
Count pairs with given sum (#10282)
* added power_of_4 * deleted power_of_4 * added pairs_with_given_sum * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * updated the comment * updated return hint * updated type hints * updated the variable * updated annotation * updated code * updated code * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * added the problem link and used defaultdict * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * corrected import formatting * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update pairs_with_given_sum.py * Update data_structures/arrays/pairs_with_given_sum.py --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Christian Clauss <cclauss@me.com>
1 parent 92fbe60 commit 09ce6b2

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
#!/usr/bin/env python3
2+
3+
"""
4+
Given an array of integers and an integer req_sum, find the number of pairs of array
5+
elements whose sum is equal to req_sum.
6+
7+
https://practice.geeksforgeeks.org/problems/count-pairs-with-given-sum5022/0
8+
"""
9+
from itertools import combinations
10+
11+
12+
def pairs_with_sum(arr: list, req_sum: int) -> int:
13+
"""
14+
Return the no. of pairs with sum "sum"
15+
>>> pairs_with_sum([1, 5, 7, 1], 6)
16+
2
17+
>>> pairs_with_sum([1, 1, 1, 1, 1, 1, 1, 1], 2)
18+
28
19+
>>> pairs_with_sum([1, 7, 6, 2, 5, 4, 3, 1, 9, 8], 7)
20+
4
21+
"""
22+
return len([1 for a, b in combinations(arr, 2) if a + b == req_sum])
23+
24+
25+
if __name__ == "__main__":
26+
from doctest import testmod
27+
28+
testmod()

0 commit comments

Comments
 (0)