-3

I'm working on a leetcode problem, and the problem is:

Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.

For example, Assume that words = ["practice", "makes", "perfect", "coding", "makes"].

Given word1 = “coding”, word2 = “practice”, return 3. Given word1 = "makes", word2 = "coding", return 1.

The code I have so far:

    class Solution(object):
    def shortestDistance(self, words, word1, word2):
        count = 0
        count2 = 0

        for i in word1:
            count+=1
            for j in word2:
                count2 += 1

            if count > count2:
                return (count-count2)
            else:
                return (count2-count1)

s = Solution()
print(s.shortestDistance(["practice", "makes", "perfect", "coding", "makes"], "coding", "practice")

I've tried messing around with the tabbing and I still can't find a right way to align the code.

*the method is indented but for some reason would not indent here just fyi

  • Copy the code you posted back into your program and all the tabs will be gone. Alternatively, hit `ctrl+h` and replace `\t` with four spaces. – Aran-Fey Mar 05 '17 at 00:53
  • Possible duplicate of ["inconsistent use of tabs and spaces in indentation"](http://stackoverflow.com/questions/5685406/inconsistent-use-of-tabs-and-spaces-in-indentation) – Juan T Mar 05 '17 at 01:12

1 Answers1

0

I'm not sure what indentation issues you're talking about - your method definition should be indented one further, but beyond that, it seems to work (meaning it runs). But your logic looks wrong, based on my understanding. Try this:

class Solution(object):
    def shortestDistance(self, words, word1, word2):
        count = 0

        for word in words:
            count += 1
            if word == word1:
                count1 = count
            if word == word2:
                count2 = count

        if count1 > count2:
            return (count1-count2)
        else:
            return (count2-count1)

s = Solution()

Note that this will have some funny behavior when you have duplicates of the same word (e.g. make and make) - it will count the position of whatever one comes last in the list. But it should be much closer to what you're trying to do.

Kewl
  • 3,327
  • 5
  • 26
  • 45