0

I should define a function overlapping() that takes two lists and returns True if they have at least one member in common, False otherwise. For the sake of the exercise, I should write it using two nested for-loops. What am I doing wrong?

def overlapping(a,b):
    for char in a:
        for char2 in b:
            return char in char2

Any suggestions how to make it work?

Gusto
  • 1,483
  • 9
  • 23
  • 34
  • See [that](http://stackoverflow.com/questions/2197482/efficiently-knowing-if-intersection-of-two-list-is-empty-or-not-in-python/2215556#2215556) answer for ideas. It is possible that you and Manuel had the same course and/or teacher. – tzot Oct 24 '10 at 21:30

3 Answers3

2

You should use == and not the in operator

def overlapping(list_a,list_b):
    for char_in_list_a in list_a:
        for char_in_list_b in list_b:
            if char_in_list_a == char_in_list_b:
                return True
    return False

If you want something using set:

def overlapping(a,b):
         return bool(set(a) & set(b))
systempuntoout
  • 71,966
  • 47
  • 171
  • 241
  • The one I'd go with if it was my code, but sadly the assignment requires nested loops. –  Oct 24 '10 at 20:23
  • This is going to return True only if a[0] == b[0] and False in every other case. – Klark Oct 24 '10 at 20:27
  • First code is completely wrong, second is basically a complete solution to a HOMEWORK task. And is wrong too, since Gusto is asked to provide a solution with two nested for-loops. – Krzysztof Bujniewicz Oct 24 '10 at 20:34
  • @raceCh For me it's irrelevant that is a Homework task. I just answer questions. For further reading, have a look at this: http://meta.stackexchange.com/questions/10811/how-to-ask-and-answer-homework-questions – systempuntoout Oct 24 '10 at 20:46
  • @systempuntoout which doesn't change the fact that both are wrong: first one contains unneeded else in improper place, second is not really answer to the question. – Krzysztof Bujniewicz Oct 24 '10 at 20:54
  • @systempuntoout I removed the downvote, since now it's correct. – Krzysztof Bujniewicz Oct 24 '10 at 21:05
2

If you really need to use 2 loops:

def overlapping(a,b):
    for char1 in a:
        for char2 in b:
            if char1 == char2: return True
    return False

But the solution with sets is much better.

Klark
  • 8,162
  • 3
  • 37
  • 61
  • This one works fine! Thanks. The set() is good too but since the nested for-loops are required I cant't use set() – Gusto Oct 24 '10 at 20:43
0

Return ends the function immediately when executed. Since this is a homework, you should figure working solution by yourself. You might consider using a set.

Krzysztof Bujniewicz
  • 2,407
  • 21
  • 16