compare list

Brian van den Broek broek at cc.umanitoba.ca
Tue Nov 15 01:40:00 EST 2005


Ben Bush said unto the world upon 2005-11-14 23:20:

<trimmed and un-top-posted>

> 
>  On 11/14/05, Brian van den Broek <broek at cc.umanitoba.ca> 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

<snip>

>>>>>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>

> what does the following code mean?
>  if item in list2:
> if item + 1 in list1 and item + 1 in list2:
>


Hey Ben,

first, as expected, the other two answers you received are better. :-)

Sets are much better optimized for things like membership testing than
are lists. I'm not competent to explain why; indeed, I keep
overlooking them myself :-(

Unfortunately, the indents got screwed up along the way. But the part
of my code you asked about was:

     for item in list1:
         if item in list2:
             if item + 1 in list1 and item + 1 in list2:
                 return True

In some detail:

Consider each item in list1 in turn. If the item isn't in list2, move
on, as there is no chance of it meeting your test. If the item is in
list2, then it is pointful to check if your test is met. Given that
you wanted consecutive numbers, the 'if item + 1 in list1 and item + 1
in list2' condition checks if both lists (which contain item if we've
gone this far) also contain item + 1. If they do, you wanted the
function to return 1 (I changed it to True as more idiomatic). After
my for loop is a return False which we will only hit if the condition
you wanted to test was never satisfied.

Does that clarify it?

Finally, your response to Alex would have been much more useful if
you'd quoted the error rather than just asserting that you got an
error :-)

Best,

Brian vdB





More information about the Python-list mailing list