Python '{}'.format() costs much time?


  • 0
    L
    class Solution:
        # @param beginWord, a string
        # @param endWord, a string
        # @param wordDict, a set<string>
        # @return an integer
        def ladderLength(self, beginWord, endWord, wordDict):
            
            if beginWord == endWord:
                return 0
            wordSet = wordDict
            wordDict = {beginWord:1}
                        
            queue = collections.deque()
            
            letters = 'abcdefghijklmnopqrstuvwxyz'
            word_len = len(beginWord)
            queue.append(beginWord)
    
            while queue:
                word = queue.popleft()
                if word == endWord:
                    return wordDict[word]
                for i in range(word_len):
                    for each in letters:
                        if each == word[i]:
                            continue
                        else:
                            # new_word = '{}{}{}'.format(word[0:i], each, word[i+1:])
                            new_word = word[0:i] + each + word[i+1:]
                            if new_word in wordSet and new_word not in wordDict:
                                queue.append(new_word)
                                wordDict[new_word] = wordDict[word] + 1
            return 0
    

    If I use new_word = word[0:i] + each + word[i+1:] instead of new_word = '{}{}{}'.format(word[0:i], each, word[i+1:]), it's AC.
    Does ''.format() function cost much time?


  • 0
    L

    'a' + 'b' + 'c' costs 26.8ns

    '{}{}{}'.format('a', 'b', 'c') costs 705ns

    Unbelievable


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.