Gusto
Gusto

Reputation: 1513

comparing two lists, python

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?

Upvotes: 0

Views: 2004

Answers (3)

systempuntoout
systempuntoout

Reputation: 74154

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))

Upvotes: 2

Klark
Klark

Reputation: 8300

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.

Upvotes: 2

Krzysztof Bujniewicz
Krzysztof Bujniewicz

Reputation: 2417

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.

Upvotes: 0

Related Questions