[英]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
假设
lst = [7,1,5,4,2,3,6]
, (7, 2), (5, 4), (6, 3)
lst = [7,1,5,4,2,3,6]
, (7, 2), (5, 4), (6, 3)
lst = [7,1,5,4,2,3,6]
, (7, 2), (5, 4), (6, 3)
lst = [7,1,5,4,2,3,6]
(7, 2), (5, 4), (6, 3)
是一些对,总共有6对增加最多9
(i) The order of numbers in a pair matters. (i)一对中的数字顺序很重要。 For example, (7, 2) and (2, 7) are two different pairs.
例如,(7,2)和(2,7)是两对不同的对。 (ii) A number cannot pair with itself.
(ii)数字不能与自身配对。 (iii) There is no duplicate element in the list
(iii)清单中没有重复的要素
def find_pairs(lst, key):
count = 0
if sum(lst[count:count+1]) == key:
count += 1
return count
else:
return find_pairs(lst[1:],key)
This is my code. 这是我的代码。 What's wrong ??
怎么了 ?? I am getting an error input
find_pairs([7,1,5,4,2,3,6], 9)
give 6
我得到一个错误输入
find_pairs([7,1,5,4,2,3,6], 9)
给6
find_pairs(list(range(1, 100, 2)), 55) #0
find_pairs(list(range(1, 100, 2)), 56) #28
There's a built-in for this in the itertools
module : 在
itertools
模块中有一个内置功能:
def find_pairs(lst, key):
return [(a,b) for a,b in itertools.permutations(lst, 2) if a+b==key]
or, more generically: 或者,更一般地说:
def find_tuples(lst, key, num=2):
return [i for i in itertools.permutations(lst, num) if sum(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)]
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]]
) 只考虑一次一个值(
lst[i:i+1]
是一个包含单个项目的切片,与[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 list (一旦修复)你的代码只考虑相邻的值对 - 在你的例子中,
(7, 2)
永远不会被找到,因为7在输入列表中不是2的旁边
using recursion for absolutely no good reason 使用递归绝对没有充分的理由
Here is a more efficient version ( O(n)
instead of O(n**2)
): 这是一个更高效的版本(
O(n)
而不是O(n**2)
):
def find_pairs_count(lst, pair_sum):
upto = (pair_sum - 1) // 2
vals = set(lst)
return 2 * sum(i <= upto and (pair_sum - i) in vals for i in lst)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.