Leetcode:Zigzag转换-代码在本地Python IDE中运行良好,但在线测试失败
嘿,伙计们, 我正试图通过上述leetcode测试。我的代码在本地运行良好,但当我提交在线测试时,它失败了:Leetcode:Zigzag转换-代码在本地Python IDE中运行良好,但在线测试失败,python,Python,嘿,伙计们, 我正试图通过上述leetcode测试。我的代码在本地运行良好,但当我提交在线测试时,它失败了: class Solution: # @return a string def convert(self, s, nRows): rowStrings = [] for i in range(0,nRows): rowStrings.append("") index = 0 direction = "DOWN" for i in
class Solution:
# @return a string
def convert(self, s, nRows):
rowStrings = []
for i in range(0,nRows):
rowStrings.append("")
index = 0
direction = "DOWN"
for i in range(0,len(s)):
rowStrings[index] = rowStrings[index] + s[i]
print index
print s[i]
if (direction == "DOWN"):
index += 1
else:
index -= 1
if (index == 0):
direction = "DOWN"
elif (index == nRows - 1):
direction = "UP"
return "".join(rowStrings)
我倾向于认为在某个地方有逻辑错误,因为我在C++和现在的Python中使用了相同的逻辑,并且我根据网站得到了运行时错误。有趣的是,在本地,答案在我的C++和Python代码中都是正确的,并且没有运行时错误发生。python错误代码更具描述性,因此我在这里发布了python代码 还有其他人经历过这样的情况吗?
range()
不包括最后一个参数的值,所以
范围(0,1)
将只生成[0]
。
然后在for
循环中,您得到索引
等于0,然后是1,这超出了行字符串的界限。
如您所见,输入参数的值等于'AB'和1。请不要发送垃圾邮件标签。这里没有C++代码,很抱歉。我把它拿走了。下次会记住的啊,我明白了。我的代码不处理nRows=1的情况。哇,这是一个微妙的错误。如何重写代码以避免此类问题?是的,我的循环风格有问题吗?我的代码跨越循环的能力是否很差?工作单元在循环中部分完成是否是一个“问题”?
from itertools import cycle
def convert(text, num_rows):
# zigzag: [0 .. num_rows-1] [num_rows-2 .. 1]
offsets = list(range(num_rows)) + list(range(num_rows - 2, 0, -1))
rows = [[] for _ in range(num_rows)]
for row, ch in zip(cycle(offsets), text):
rows[row].append(ch)
rows = ["".join(row) for row in rows]
return "".join(rows)
Runtime Error Message: Line 12: IndexError: list index out of range
Last executed input: "AB", 1
from itertools import cycle
def convert(text, num_rows):
# zigzag: [0 .. num_rows-1] [num_rows-2 .. 1]
offsets = list(range(num_rows)) + list(range(num_rows - 2, 0, -1))
rows = [[] for _ in range(num_rows)]
for row, ch in zip(cycle(offsets), text):
rows[row].append(ch)
rows = ["".join(row) for row in rows]
return "".join(rows)