Youssef Abdeen
Youssef Abdeen

Reputation: 49

Counting pairs of numbers that adds up to a specific value in Python

i want to count how many pairs of numbers in a list can add to a specific number, this is my code in python but the output is not what it should be

list = [1,2,3,4]
x=3
count = 0
for i in range(len(list)):
for j in range(len(list)):
if i + j == x:
count+=1
print(count)

Upvotes: 0

Views: 45

Answers (2)

Mike
Mike

Reputation: 803

You could simpilify your code with functions from the built-in itertools module, depending on how you would like to iterate through the list, i.e. combinations, combinations with replacements, or products.

import itertools as itt

in_list = [1,2,3,4]
tgt_num = 3
count = 0
for a,b in itt.combinations(in_list, 2): # returns 1
# for a,b in itt.combinations_with_replacement(in_list, 2): # returns 1
# for a,b in itt.product(in_list, in_list): # returns 2
    if a + b == tgt_num:
            count += 1
print(count)

Upvotes: 1

Josh Rockefeller
Josh Rockefeller

Reputation: 1

Your code has some issues: One is that it never directly references the items of the list. Because of this, it will only work assuming that the numbers in the list are in ascending order, each is one apart, and that it starts at 1. Another is that it iterates through the pairs of numbers too many times. Finally, there are some indentation issues, but I'm guessing those were just lost in the copy-paste. I tried to re-indent it, but when I ran it I got "4", when it should be "1". Here's a version that incorporates indexing the list, which should resolve the above issues.

list = [1,2,3,4]
x = 3
count = 0
for i in range(0,len(list)):
    pair1 = list[i]
    pair2 = list[i+1:]
    for j in range(0,len(pair2)):
        if pair1 + pair2[j] == x:
            count += 1
print(count)

Upvotes: 0

Related Questions