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

前端 未结 12 841
予麋鹿
予麋鹿 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:16

    from itertools import izip
    
    def is_neighbors(word1,word2):
        different = False
        for c1,c2 in izip(word1,word2):
            if c1 != c2:
                if different:
                    return False
                different = True
        return different
    

    Or maybe in-lining the izip code:

    def is_neighbors(word1,word2):
        different = False
        next1 = iter(word1).next
        next2 = iter(word2).next
        try:
            while 1:
                if next1() != next2():
                    if different:
                        return False
                    different = True
        except StopIteration:
            pass
        return different
    

    And a rewritten getchildren:

    def iterchildren(word, wordlist):
        return ( w for w in wordlist if is_neighbors(word, w) )
    
    • izip(a,b) returns an iterator over pairs of values from a and b.
    • zip(a,b) returns a list of pairs from a and b.

提交回复
热议问题