compare list

Brian van den Broek broek at cc.umanitoba.ca
Tue Nov 15 02:16:38 CET 2005


Ben Bush said unto the world upon 2005-11-14 05:51:
> I have four lists:
> lisA=[1,2,3,4,5,6,9]
> lisB=[1,6,5]
> lisC=[5,6,3]
> lisD=[11,14,12,15]
> how can I write a function to compare lisB, lisC and lisD with lisA, if they
> share two continuous elements (the order does not matter), then return 1,
> otherwise return 0. For example, lisA, lisB and lisC have 5,6 or 6,5 so
> these comparison will return 1 but the comparison between lisD and lisA
> return 0.
> --
> Thanks!
> Ben Bush

Hi Ben,

the code below is tested no further than shown. And, I'm no expert -- 
I imagine there are better ways. With luck, I'll learn them in a 
follow-up from someone more skilled :-)

 >>> def list_common_continuity_comp(list1, list2):
         for item in list1:
                 if item in list2:
                         if item + 1 in list1 and item + 1 in list2:
                                 return True
         return False

 >>> lisA=[1,2,3,4,5,6,9]
 >>> lisB=[1,6,5]
 >>> lisC=[5,6,3]
 >>> lisD=[11,14,12,15]
 >>> list_common_continuity_comp(lisA, lisB)
True
 >>> list_common_continuity_comp(lisA, lisC)
True
 >>> list_common_continuity_comp(lisA, lisD)
False
 >>> list_common_continuity_comp(lisD, lisA)
False
 >>> list_common_continuity_comp(lisA, lisA)
True
 >>> list_common_continuity_comp(lisB, lisA)
True


That gets you a binary comparison. To make it a polyadic:


 >>> def multi_list_continuity_comp(list_of_lists):
         list1 = list_of_lists[0]
         for other_list in list_of_lists[1:]:
                 if not list_common_continuity_comp(list1, other_list):
                         return False
         return True

 >>> meta_list1 = [lisA, lisB, lisC, lisD]
 >>> meta_list2 = meta_list1[:-1]
 >>> multi_list_continuity_comp(meta_list1)
False
 >>> multi_list_continuity_comp(meta_list2)
True
 >>>


Some edge cases haven't been handled:

 >>> multi_list_continuity_comp([])

Traceback (most recent call last):
   File "<pyshell#101>", line 1, in -toplevel-
     multi_list_continuity_comp([])
   File "<pyshell#95>", line 2, in multi_list_continuity_comp
     list1 = list_of_lists[0]
IndexError: list index out of range
 >>>

but this should get you started.

Best,

Brian vdB




More information about the Python-list mailing list