Find The Number Of Pairs In List
Suppose lst = [7,1,5,4,2,3,6], (7, 2), (5, 4), (6, 3) are some of the pairs and in total there are 6 pairs that adds up to 9 (i) The order of numbers in a pair matters. For exampl
Solution 1:
There's a built-in for this in the itertools
module:
deffind_pairs(lst, key):
return [(a,b) for a,b in itertools.permutations(lst, 2) if a+b==key]
or, more generically:
deffind_tuples(lst, key, num=2):
return [i for i in itertools.permutations(lst, num) ifsum(i)==key]
You can use it like this:
>>>find_tuples(lst, 9)
[(7, 2), (5, 4), (4, 5), (2, 7), (3, 6), (6, 3)]
>>>find_tuples(lst, 9, 3)
[(1, 5, 3), (1, 2, 6), (1, 3, 5), (1, 6, 2), (5, 1, 3), (5, 3, 1), (4, 2, 3),
(4, 3, 2), (2, 1, 6), (2, 4, 3), (2, 3, 4), (2, 6, 1), (3, 1, 5), (3, 5, 1),
(3, 4, 2), (3, 2, 4), (6, 1, 2), (6, 2, 1)]
Solution 2:
Your code is
only considering a single value at a time (
lst[i:i+1]
is a slice containing a single item, identical to[lst[i]]
)(once that is fixed) your code only considers adjacent pairs of values - in your example,
(7, 2)
would never be found because 7 is not next to 2 in the input listusing recursion for absolutely no good reason
Here is a more efficient version (O(n)
instead of O(n**2)
):
deffind_pairs_count(lst, pair_sum):
upto = (pair_sum - 1) // 2
vals = set(lst)
return2 * sum(i <= upto and (pair_sum - i) in vals for i in lst)
Post a Comment for "Find The Number Of Pairs In List"