1
a = [1,2,3,4,5,6,7]
b  = [56,59,62,65,67,69]


def sumOfTwo(a,b,v):
    for i in range (len(a)):
        val_needed = v - a[i]
        for j in range (len(b)):
            if b[j] == val_needed:
                x = b[j]
                y = a[i]             
    print(x,y) 

sumOfTwo(a,b,v=70)

Output: 5 65

What if more pairs are possible from the given lists in the problem, how do I do that? Help. What are more ways to achieve this?

Avinash Singh
  • 122
  • 2
  • 9
  • Here you are printing out the **last** pair that matches. If you want to print **all** pairs that match, then you need the `print()` inside the `for` loops. – Code-Apprentice Feb 21 '20 at 16:58
  • Thanks Code.Apprentice. You were quick. It takes O(n^2), can we reduce the time complexity? – Avinash Singh Feb 21 '20 at 17:02
  • 1
    That's a different question than what you originally asked. My first inclination is probably not. You might be able to reduce the constant factor if you know that both input lists are sorted. This will allow you to break as soon as the sum of two elements is larger than the target. – Code-Apprentice Feb 21 '20 at 17:11

2 Answers2

3

If you just want to print matched values, you just have to indent the print statement to be inside theif, as stated below. Also, you should use a more pythonic approach to for loops and also for variable assignments.

a = [1,2,3,4,5,6,7]
b  = [56,59,62,65,67,69]


def sumOfTwo(a,b,v):
    for i in a:
        val_needed = v - i
        for j in b:
            if j == val_needed:
                x, y = j, i
                print(x,y)

sumOfTwo(a,b,v=70)
2

Using a list comprehension:

a = [1,2,3,4,5,6,7]
b = [56,59,62,65,67,69]

c = [(x, y)
     for x in a
     for y in b
     if x + y == 70]

print(c)

This yields

[(1, 69), (3, 67), (5, 65)]
Jan
  • 42,290
  • 8
  • 54
  • 79