views:

77

answers:

3

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?

A: 

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.

raceCh-
+2  A: 

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
The one I'd go with if it was my code, but sadly the assignment requires nested loops.
delnan
Um, the added code is wrong, for the very reason raceCh- names...
delnan
This is going to return True only if a[0] == b[0] and False in every other case.
Klark
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.
raceCh-
@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.stackoverflow.com/questions/10811/how-to-ask-and-answer-homework-questions
systempuntoout
@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.
raceCh-
@systempuntoout I removed the downvote, since now it's correct.
raceCh-
+2  A: 

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
This one works fine! Thanks.The set() is good too but since the nested for-loops are required I cant't use set()
Gusto