-2

If I have two list such as

list1 = ['cat', 'sat', 'on', 'mat', 'xx', 'yy'] ,
list2 = ['cow', 'sat', 'on', 'carpet', 'xx', 'yy']

I have walk along the lists: when I see two elements that match, start counting. when I see another pair of elements that don't match, stop that counter and start another one.

(sat, sat) I = 1

(on, on) I = 2

(mat, carpet) J = 1

(xx, xx) k = 1

(yy, yy) k = 2

i = 0
for x in list1:
    for y in list2:
        if x == y:
            print (x, y)
            i += 1
        else:
            j = 0
            j += 1
            print (x, y)
Artjom B.
  • 59,901
  • 24
  • 121
  • 211
user3657345
  • 17
  • 1
  • 8

2 Answers2

0

What about the following :

def doit(list1, list2):
    lastmatch = -1
    lastunmatch = -1
    for i, x in enumerate(zip(list1, list2)):
        if x[0] == x[1]:
            lastmatch = i                
        else:
            lastunmatch = i
        print abs(lastmatch - lastunmatch)

Running : http://ideone.com/xnJWtz

Danstahr
  • 4,060
  • 19
  • 36
0
>>> from collections import defaultdict
>>>
>>> list1 = ['cat', 'sat', 'on', 'mat', 'xx', 'yy']
>>> list2 = ['cow', 'sat', 'on', 'carpet', 'xx', 'yy']
>>>
>>> var_it = iter('IJKLMNOPQRSTUVWXYZ') # variable candidates
>>> counters = defaultdict(int)
>>> c = next(var_it)
>>> for word1, word2 in zip(list1, list2):
...     if word1 == word2:
...         counters[c] += 1
...     else:
...         if counters: # Prevent counting until first match
...             counters[next(var_it)] = 1
...             c = next(var_it)
...
>>> for var in sorted(counters):
...     print('{}: {}'.format(var, counters[var]))
...
I: 2
J: 1
K: 2
falsetru
  • 336,967
  • 57
  • 673
  • 597