Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Your function <code>distance</code> is calculating the total distance, when you really only care about distance=1. The majority of cases you'll know it's >1 within a few characters, so you could return early and save a lot of time.</p> <p>Beyond that, there might be a better algorithm, but I can't think of it.</p> <p><b>Edit:</b> Another idea.</p> <p>You can make 2 cases, depending on whether the first character matches. If it doesn't match, the rest of the word has to match exactly, and you can test for that in one shot. Otherwise, do it similarly to what you were doing. You could even do it recursively, but I don't think that would be faster.</p> <pre><code>def DifferentByOne(word1, word2): if word1[0] != word2[0]: return word1[1:] == word2[1:] same = True for i in range(1, len(word1)): if word1[i] != word2[i]: if same: same = False else: return False return not same </code></pre> <p><b>Edit 2:</b> I've deleted the check to see if the strings are the same length, since you say it's redundant. Running <a href="https://stackoverflow.com/questions/788084/how-can-i-optimize-this-python-code/788168#788168">Ryan's tests</a> on my own code and on the is_neighbors function <a href="https://stackoverflow.com/questions/788084/how-can-i-optimize-this-python-code/788113#788113">provided by MizardX</a>, I get the following:</p> <ul> <li>Original distance(): 3.7 seconds</li> <li>My DifferentByOne(): 1.1 seconds</li> <li>MizardX's is_neighbors(): 3.7 seconds</li> </ul> <p><b>Edit 3:</b> (Probably getting into community wiki territory here, but...)</p> <p>Trying your final definition of is_neighbors() with izip instead of zip: 2.9 seconds.</p> <p>Here's my latest version, which still times at 1.1 seconds:</p> <pre><code>def DifferentByOne(word1, word2): if word1[0] != word2[0]: return word1[1:] == word2[1:] different = False for i in range(1, len(word1)): if word1[i] != word2[i]: if different: return False different = True return different </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload