I have two lists in python.Now I want to write a code which will search for the elements in the two lists.If they have the same element it return true else false.
Repetitions are allowed and the order could be different.
I do not want to use the "set" in-build function(Because it makes it so easy) or I don't want to do something like this:
for item1, item2 in zip(list1, list2):
if(list1 == list2):
Because this can be done only when there are same number of elements and order is same
The sensible way to do this is to use sets. But if you insist on doing it inefficiently by looping, then you need to check that each element of the first list is an element of the second list, and vice versa.
Here are 3 ways to do that check. Notice that (unlike the code in your earlier question) I'm directly iterating over the list elements; there is no need to use list indices for this task in Python.
Firstly, we use an explicit flag
ok to keep track of matches.
#Test if each element of `b` is also an element of `a` def contains(a, b): for v in b: ok = False for u in a: if v == u: ok = True break if not ok: return False return True
This can be condensed by attaching an
else clause to the inner
def contains(a, b): for v in b: for u in a: if v == u: break else: return False return True
But we can make it even shorter by using the built-in
any function and a generator expression:
def contains(a, b): for v in b: if not any(v == u for u in a): return False return True
any(v == u for u in a) will stop testing as soon as it finds a
u that matches
Now for the full matching test. This code works on Python 2 or Python 3.
from __future__ import print_function def contains(a, b): for v in b: if not any(v == u for u in a): return False return True def match(a, b): return contains(a, b) and contains(b, a) target = [1,2,3,4,5] data = ([3,5,1,2,4], [1,2,3,4,5,6], [1,2,3,4,6], [3,1,2,1,4]) print(target) for seq in data: print(seq, contains(target, seq), contains(seq, target), match(target, seq))
[1, 2, 3, 4, 5] [3, 5, 1, 2, 4] True True True [1, 2, 3, 4, 5, 6] False True False [1, 2, 3, 4, 6] False False False [3, 1, 2, 1, 4] True False False