Find position 1 where the two lists are the same

The challenge is to write a function to compare two fairly small lists of integers (basically, less than 10 elements). One list might be something like this:

self = [0, 0, 1, 2] 

The lists that need to be matched may look like one of the following examples:

 other1 = [] other2 = [0, 0, 1] other3 = [0, 0, 1, 2, 0] other4 = [0, 1, 1, 2] other5 = something 

As you can see, duplicate elements are quite common, and the order of the elements is important.

The expected result should be an integer representing how long I and the others are the same, counted from the very beginning. Thus, depending on the other, the result will be:

 result1 = 0 result2 = 3 result3 = 4 result4 = 1 result5 = 0 

The code should be the most efficient, as it should be used approximately 100 times for each user interaction.

I encoded the following, it works as it wants, but it seems slow:

 def match(self, other): if self == other: return len(self) element = -1 for element in range(min(len(self), len(other))): if self[element] != other[element]: element -= 1 break return element +1 

The first if statement is already an improvement to speed things up, but the solution still seems slow and also looks a bit awkward with all its corrections to a variable called element and two return statements.

Does anyone have a name for a function that is better than match or compare?

+3
source share
3 answers

In a related question, I posted the following possible solutions:

 def while_equal(seq, other): for this, that in zip(seq, other): if this != that: return yield this def match(seq, other): return sum(1 for _ in while_equal(seq, other)) 

and

 def match_loop(seq, other): count = 0 for this, that in zip(seq, other): if this != that: return count count += 1 return count 

These versions are faster than other preset solutions (the second is the fastest), and, I would say, more readable.

+1
source
 >>> from itertools import takewhile, izip >>> def F(seq1, seq2): return sum(1 for x in takewhile(lambda x: x[0] == x[1], izip(seq1, seq2))) >>> F([0, 0, 1, 2], [0, 0, 1, 2, 0]) 4 
+4
source

Edit: as Jamilak pointed out, my decision is wrong. I will save it here so that anyone who wants to answer this question will see the whole problem, not just the first two cases.

Another solution that does not require itertools , although it will not be as effective as a jamylak solution .

 def compareLists(list1, list2): return sum(map(lambda (x,y): 1 if x == y else 0, zip(list1, list2))) 
0
source

All Articles