0

I got an assignment in my CS class: to find pairs of numbers in a list, that add to a number n, that is given. This is the code I wrote for it:

def pair (n, num_list):    
    """
    this function return the pairs of numbers that add to the value n.
    param: n: the value which the pairs need to add to.
    param: num_list: a list of numbers.
    return: a list of all the pairs that add to n.
    """    
    for i in num_list:
        for j in num_list:
            if i + j == n:
                return [i,j]
                continue

When I try to run it, I'm given the following message:

TypeError("'int' object is not iterable",)

What is the problem? I can't find a place in which I use a list obj as an int, or vice versa.

PM 2Ring
  • 54,345
  • 6
  • 82
  • 182
mizenetofa1989
  • 117
  • 2
  • 16
  • http://stackoverflow.com/questions/1938227/int-object-is-not-iterable – Eray Balkanli Nov 07 '15 at 17:42
  • Hi, I tried your function with >>> pair(4, [1,2,3]) [1, 3] and it works – Jean-Claude Colette Nov 07 '15 at 17:50
  • 1). You're passing an integer instead of a list of numbers as the 2nd argument of `pair`. 2) But even if you _do_ call it properly your `pair` function will only return a list of the first pair it finds. You need to collect those pairs into a master list and return that list once you've tested every pair. 3). You code will test if a number in `num_list` pairs with itself, which may be ok. But it tests every other pair twice, which may not be ok. – PM 2Ring Nov 07 '15 at 17:50

2 Answers2

0

num_list must be iterable.

Your code return first pair, not all pairs.

Read about List Comprehensions

[[i, j] for i in num_list for j in num_list if i + j == n]
Tomasz Jakub Rup
  • 10,502
  • 7
  • 48
  • 49
0

If you want to use your function like a list, you can yield the values instead of returning them:

def pair (n, num_list):       
    for i in num_list:
        for j in num_list:
            if i + j == n:
                yield i, j

More info here: https://www.jeffknupp.com/blog/2013/04/07/improve-your-python-yield-and-generators-explained/

Joe
  • 2,496
  • 1
  • 22
  • 30