Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the 1 based position to which two lists are the same

Tags:

python

list

The challange is to write a function to compare two rather small lists of integers (mostly less than 10 elements each). One list could be something like:

self = [0, 0, 1, 2]

The lists which it is to be compared with could 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 elements is important.

The expected result should be an integer, representing how long self and other are the same, counted from the beginning. So depending on other, the result would be:

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

The code should be most efficient, since it is to be used some 100 times for every user interaction.

I coded the following, it works as desired, but seems to be kind of 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 enhancement to speed things up, but the solution still seems slow and also looks a bit clumsy with all its corrections to the variable named element and the two return statements.

Has anybody a name for such a function which is better than 'match' or 'compare'?

like image 734
Richard Avatar asked Nov 26 '25 16:11

Richard


1 Answers

>>> 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
like image 174
jamylak Avatar answered Nov 28 '25 17:11

jamylak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!