接收TabError:python程序缩进中制表符和空格的使用不一致
我正在处理一个leetcode问题,问题是: 给定一个单词列表和两个单词word1和word2,返回列表中这两个单词之间的最短距离 比如说,, 假设单词=[“练习”、“制造”、“完美”、“编码”、“制造”] 给定word1=“编码”,word2=“实践”,返回3。 给定word1=“makes”,word2=“coding”,返回1 到目前为止,我掌握的代码是:接收TabError:python程序缩进中制表符和空格的使用不一致,python,Python,我正在处理一个leetcode问题,问题是: 给定一个单词列表和两个单词word1和word2,返回列表中这两个单词之间的最短距离 比如说,, 假设单词=[“练习”、“制造”、“完美”、“编码”、“制造”] 给定word1=“编码”,word2=“实践”,返回3。 给定word1=“makes”,word2=“coding”,返回1 到目前为止,我掌握的代码是: class Solution(object): def shortestDistance(self, words, w
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")
我尝试过使用标签,但仍然找不到正确的方法来对齐代码
*方法是缩进的,但出于某种原因,这里不会缩进仅供参考我不确定您在谈论什么缩进问题-您的方法定义应该进一步缩进,但除此之外,它似乎可以工作(意味着它可以运行)。但根据我的理解,你的逻辑看起来是错误的。试试这个:
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()
请注意,当您有相同单词的副本时(例如make和make),这将有一些有趣的行为-它将计算列表中最后一个单词的位置。但是它应该更接近您要做的事情。将您发布的代码复制回您的程序中,所有选项卡都将消失。或者,点击
ctrl+h
,并用四个空格替换\t
。可能重复