1

I have a problem to count pairs in list A[4, 8, 9, 0, 12, 1, 4, 2, 12, 12, 4, 4, 8, 11, 12, 0] that equals 12. i'm trying to code it in Python, but still i get pairs repeated...

def printPairs(arr, arr_size, sum):
    # Create an empty hash set
    s = set()
    
    for i in range(0, arr_size):
        temp = sum-arr[i]
        if (temp in s):
            print ("Pair with given sum "+ str(sum) +
            " is (" + str(arr[i]) + ", " + str(temp) + ")") +
            s.add(arr[i])
# driver code
A = [4, 8, 9, 0, 12, 1, 4, 2, 12, 12, 4, 4, 8, 11, 12, 0]
n = 12
printPairs(A, len(A), n)

Solution what i want must be [0, 12], [4, 8], [4, 8], [11, 1], [12 ,0].

Could you help me?

azro
  • 53,056
  • 7
  • 34
  • 70
robsson
  • 11
  • 2
  • In your "solution I want' you have a repeated pair, so ? – azro Apr 30 '21 at 08:29
  • Does it correspond to what you do want -> [find all combinations of a list of numbers with a given sum](https://stackoverflow.com/questions/34517540/find-all-combinations-of-a-list-of-numbers-with-a-given-sum)? – AvyWam Apr 30 '21 at 09:18

2 Answers2

0
  • The check need to be if temp in arr[i + 1:], because as s is empty you'll never go in it, you need to check if the value is present later in the array
  • Add pairs in s, not one item, do s.add((arr[i], temp))
def printPairs(arr, count):
    s = set()
    for i in range(len(arr)):
        temp = count - arr[i]
        if temp in arr[i + 1:]:
            print("Pair with given sum ", count, " is (", arr[i], ",", temp, ")")
            s.add((arr[i], temp))
    return s

Result

res = printPairs([4, 8, 9, 0, 12, 1, 4, 2, 12, 12, 4, 4, 8, 11, 12, 0], 12)
print(res)  # {(11, 1), (8, 4), (1, 11), (12, 0), (0, 12), (4, 8)}

To get {(0, 12), (1, 11), (4, 8)} to avoid non-ordered duplicates, use

s.add(tuple(sorted((arr[i], temp))))

# instead of
s.add((arr[i], temp))
azro
  • 53,056
  • 7
  • 34
  • 70
0

You can keep track of used indexes (not elements) to make sure an element is taken only once:

def pairs(ls, target):
    used = set()

    for i in range(len(ls)):
        if i not in used:
            for k in range(i + 1, len(ls)):
                if k not in used and ls[i] + ls[k] == target:
                    yield ls[i], ls[k]
                    used.add(k)
                    break


print(list(pairs([0, 1, 1, 0, 2, 3], 3)))  # [(0, 3), (1, 2)]
georg
  • 211,518
  • 52
  • 313
  • 390