Python 3 lines solution

  • 6
    class Solution(object):
        def shortestDistance(self, words, word1, word2):
            w1 = [i for i in xrange(len(words)) if words[i] == word1]
            w2 = [i for i in xrange(len(words)) if words[i] == word2]
            return min([abs(i - j) for i in w1 for j in w2])

    Just use list comprehension to make the code shorter.

  • 0

    Is doing a list comprehension like this the same / any different from O(n^2)? Like there isn't anything special about this usage of the data that necessarily makes it better than just nested fors, is there?


  • 0

    As I know, list comprehension is more pythonic and faster than nested block.

    For example, you want to get a list of result:

    def test1():
        result = []
        for i in xrange(10000):
            for j in xrange(10000):
                result.append(i + j)
        return result
    def test2():
        return [i + j for i in xrange(10000) for j in xrange(10000)]
    import time
    t1 = time.time()
    print time.time() - t1 # 10.9260520935
    t2 = time.time()
    print time.time() - t2 # 5.45107913017

  • 0

    This is o(n^2). Might look good but not efficient

Log in to reply

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