compare list

Duncan Smith buzzard at urubu.freeserve.co.uk
Mon Nov 14 21:45:10 EST 2005


Brian van den Broek wrote:
> 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
> 

[snip]

That's potentially very expensive for large lists, although simply
converting the lists to sets should give a significant speed up.  I
think the following is *possibly* as good a way as any.

>>> def compare(list1, list2):
	intersection = sorted(list(set(list1) & set(list2)))
	for i in range(len(intersection) - 1):
		if intersection[i] == intersection[i+1] - 1:
			return True
	return False

Duncan



More information about the Python-list mailing list