Find The 1 Based Position To Which Two Lists Are The Same
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 l
Solution 1:
>>> from itertools import takewhile, izip
>>> defF(seq1, seq2):
returnsum(1for x in takewhile(lambda x: x[0] == x[1], izip(seq1, seq2)))
>>> F([0, 0, 1, 2], [0, 0, 1, 2, 0])
4
Solution 2:
In a related question, I posted the following potential solutions:
def while_equal(seq, other):
forthis, that in zip(seq, other):
ifthis != that:
return
yield this
def match(seq, other):
return sum(1for _ in while_equal(seq, other))
and
def match_loop(seq, other):
count = 0forthis, that in zip(seq, other):
ifthis != that:
return count
count += 1return count
These versions are both faster than the other given solutions (the second being the fastest), and, I would argue, more readable.
Solution 3:
Edit: as jamylak pointed out, mine solution is wrong. I'll keep it here so everyone who wants to answer this question will see the whole problem, not just first two cases.
Yet another solution which doesn't require itertools
, though it'll be not as efficient as jamylak's solution.
defcompareLists(list1, list2):
returnsum(map(lambda (x,y): 1if x == y else0, zip(list1, list2)))
Post a Comment for "Find The 1 Based Position To Which Two Lists Are The Same"