Tabzzy
Tabzzy

Reputation: 15

How to create a function that uses 2 integers from 2 different lists and adding the pair to a certain integer?

Doing some basic python coding. Here is the problem I was presented.

Create a function that takes 3 inputs:

Prints the pairs of integers, one from the first input list and the other form the second list, that adds up to n. Each pair should be printed.

Final Result (Example):

pair([2,3,4], [5,7,9,12], 9)

2 7

4 5

I'm still awfully new to Python, studying for a test and for some reason this one keeps giving me some trouble. This is an intro course so basic coding is preferred. I probably won't understand most advanced coding.

Upvotes: 1

Views: 470

Answers (1)

Brendan Abel
Brendan Abel

Reputation: 37549

The simplest naieve approach would be to just test all possible combinations to see if they add up.

def pair(list1, list2, x):
    for a in list1:
        for b in list2:
            if a + b == x:
                print a, b

There are more efficient ways to do it (eg. ignore duplicates, ignore numbers greater than x, etc.)

If you wanted to do it in a single loop, python has some convenience functions for that

from itertools import product

for a, b in product(list1, list2):
    if a + b == x:
        print a, b

Upvotes: 1

Related Questions