comparing two lists, python
I should define a function overlapping() that takes two lists and returns True if they have at l开发者_如何学JAVAeast 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?
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.
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))
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.
精彩评论