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?

1
  • See that answer for ideas. It is possible that you and Manuel had the same course and/or teacher. Commented Oct 24, 2010 at 21:30

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

6 Comments

The one I'd go with if it was my code, but sadly the assignment requires nested loops.
This is going to return True only if a[0] == b[0] and False in every other case.
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 For me it's irrelevant that is a Homework task. I just answer questions. For further reading, have a look at this: meta.stackexchange.com/questions/10811/…
@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.
|
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.