How can I optimize this Python code to generate all words with word-distance 1?

前端 未结 12 1036
予麋鹿
予麋鹿 2021-01-30 22:11

Profiling shows this is the slowest segment of my code for a little word game I wrote:

def distance(word1, word2):
    difference = 0
    for i in range(len(word         


        
12条回答
  •  感动是毒
    2021-01-30 22:33

    I don't know if it will significantly affect your speed, but you could start by turning the list comprehension into a generator expression. It's still iterable so it shouldn't be much different in usage:

    def getchildren(word, wordlist):
        return [ w for w in wordlist if distance(word, w) == 1 ]
    

    to

    def getchildren(word, wordlist):
        return ( w for w in wordlist if distance(word, w) == 1 )
    

    The main problem would be that a list comprehension would construct itself in memory and take up quite a bit of space, whereas the generator will create your list on the fly so there is no need to store the whole thing.

    Also, following on unknown's answer, this may be a more "pythonic" way of writing distance():

    def distance(word1, word2):
        difference = 0
        for x,y in zip (word1, word2):
            if x == y:
                difference += 1
        return difference
    

    But it's confusing what's intended when len (word1) != len (word2), in the case of zip it will only return as many characters as the shortest word. (Which could turn out to be an optimization...)

提交回复
热议问题