# compare list

Bengt Richter bokr at oz.net
Wed Nov 16 02:38:24 CET 2005

```On 15 Nov 2005 04:51:05 -0800, "bonono at gmail.com" <bonono at gmail.com> wrote:

>
>Simon Brunning wrote:
>> On 15/11/05, Ben Bush <pythonnew at gmail.com> wrote:
>> > I found I named the following python file as sets.py, which brought the
>> > problem (is that right?). i changed it to other name and it works.
>> > But the logic output is wrong.
>> > from sets import Set as set
>> > lisA=[1,2,5,9]
>> > lisB=[9,5,0,2]
>> > lisC=[9,5,0,1]
>> > def two(sequence1, sequence2):
>> >    set1, set2 = set(sequence1), set(sequence2)
>> >    return len(set1.intersection(set2)) == 2
>> >  print two(lisA,lisB)
>> > False(should be true!)
>>
>> It looks to me like A and B have three members in common - 2, 5 and 9.
>>
>Any chance that while "two" performs correctly for what is intended, it
>is not what the OP wants ?
>
>Seems that he only thins the "5,9"/"9,5" are the common case, thus
>expect 2 ?
>
That's what I thought, hence:

>>> lisA=[1,2,3,4,5,6,9]
>>> lisB=[1,6,5]
>>> lisC=[5,6,3]
>>> lisD=[11,14,12,15]
>>> def pairs(seq):
...     it = iter(seq)
...     curr = it.next()
...     while True:
...         curr, last = it.next(), curr
...         yield curr, last
...         if curr != last:
...             yield last, curr
...
>>> list(pairs(lisA))
[(2, 1), (1, 2), (3, 2), (2, 3), (4, 3), (3, 4), (5, 4), (4, 5), (6, 5), (5, 6), (9, 6), (6, 9)]
>>> list(pairs(lisB))
[(6, 1), (1, 6), (5, 6), (6, 5)]
>>> set(pairs(lisA)).intersection(set(pairs(lisB)))
set([(5, 6), (6, 5)])
>>> len(set(pairs(lisA)).intersection(set(pairs(lisB)))) == 2
True

I guess the OP meant exactly one shared order-insensitive pair, so that last test is insufficient.
Maybe (untested beyond what you see ;-)

>>> def lisCheck(L1, L2):
...     common = set(pairs(L1)).intersection(set(pairs(L2)))
...     if len(common) == 1: return True  # [(x,y)] not possible since pairs makes (y,x)
...     elif len(common) == 2:            # guard against [(x,x), (y,y)]
...         t0, t1 = common
...         return t0[0]==t1[1] and t0[1]==t1[0] and t0[0]!=t0[1]
...     else: return False
...
>>> lisCheck(lisA, lisB)
True
>>> lisCheck(lisA, lisC)
True
>>> lisCheck(lisB, lisC)
True
>>> lisCheck(lisB, [5,3,6])
False
>>> lisCheck([1,2,2,3], [2,2])
True
>>> lisCheck([1,2,2,3,3], [2,2])
True
>>> lisCheck([1,2,2,3,3], [2,2,3])
False
>>> lisCheck([1,2,2,3,3], [2,2,0, 3])
True
>>> lisCheck([1,2,2,3,3], [2,2,0,3,3])
False

Also, too lazy to make pairs produce less redundant pairs than eliminating equal flips.
If I did it again, I guess I'd also yield last,curr before curr,last for better
left-to-right scan mnemonics, though it doesn't affect the end result.

Regards,
Bengt Richter

```