def count_pairs(num_list): Given a list of numbers num_list, count how many ways unique pairs of values from this list have a sum equal to a value anywhere in the list (including equaling one of the values being added). Watch out for duplicates – two locations may sum up to a value equal to many places in the list, but they only count as one pairing overall. The two summed values must be at unique locations in the list. • Parameters: num_list is a list (length > 2) of integers (no validation needed) • Examples: count_pairs([1,2,3,4,5]) → 4 # 1+2=3 # 1+3=4 # 1+4=5 # 2+3=5
count_pairs([1,2,3,1,0]) → 7 # 1+2=3 # 1+1=2 # 1+0=1 # 2+1=3 # 2+0=2 # 3+0=3 # 1+0=1
in python
Code:
def count_pairs(num_list):
ans = 0#stores answer
for i in range(len(num_list)):#traverse over the list
for j in range(i + 1, len(num_list)):#traverse over other numbers
other than the one pointed by i
if num_list[i] + num_list[j] in num_list:#if the sum of both the
numbers exists in the list
ans = ans +1#increment ans
return ans
print(count_pairs([1,2,3,1,0]))
Image of code:
Output:
Get Answers For Free
Most questions answered within 1 hours.