RFC - n-puzzle.py

Peter Otten __peter__ at web.de
Sat May 19 11:38:05 EDT 2007


Steve Holden wrote:

> Phoe6 wrote:
>> On May 19, 2:23 pm, Raymond Hettinger <pyt... at rcn.com> wrote:
>>> Instead of:
>>>     short_path = mdists[0]
>>>     if mdists.count(short_path) > 1:
>>> write:
>>>     short_path = mdists[0]
>>>     if short_path in mdists[1:]:
>> 
>> I would like to understand the difference between the two if
>> statements.
>> I had used count method, to signify the meaning that, if the least
>> distance occurs more then proceed with block.
>> How is 'in' with list[1:] an advantage? If it is.
> 
> Because it can stop as soon as short_path is found, whereas the count
> method must examine all elements to determine whether they should
> increment the count beyond one.

It's a trade-off. You check only half (on average) of the items in the
original list, but in exchange copy all but one into a new list.
The idiom Raymond recommended only makes sense because comparison is "slow"
and slicing is "fast" in Python. 

If the original list were large in comparison to the available RAM the
following idiom might be preferrable:

it = iter(mdists)
short_path = it.next()
if short_path in it:
    # ...

Peter



More information about the Python-list mailing list