RFC - n-puzzle.py

Steve Holden steve at holdenweb.com
Sat May 19 13:34:56 EDT 2007


Peter Otten wrote:
> 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. 
> 
That's true.

> 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:
>     # ...

Yes, that would nail it. Though of course it loses the obviousness which 
both original solutions have. I suppose that's often the nature of 
optimizations, though.

regards
  Steve
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd           http://www.holdenweb.com
Skype: holdenweb      http://del.icio.us/steve.holden
------------------ Asciimercial ---------------------
Get on the web: Blog, lens and tag your way to fame!!
holdenweb.blogspot.com        squidoo.com/pythonology
tagged items:         del.icio.us/steve.holden/python
All these services currently offer free registration!
-------------- Thank You for Reading ----------------




More information about the Python-list mailing list