【发布时间】:2019-12-26 14:14:55
【问题描述】:
我正在执行以下任务:给定一个大小为 m x n 的 2D 网格和一个整数 k。您需要将网格移动 k 次。
所以想出了以下代码,它工作得很好:
"""
:type grid: List[List[int]]
:type k: int
:rtype: List[List[int]]
"""
class Solution(object):
def shiftGrid(self, grid, k):
#convert grid into 1D list conv
conv = sum(grid, [])
#pre-calculating length of list to save runtime
length = len(conv)
#pre-calculating last element of list to save runtime
last = length-1
# calculate the number of grids so we can separate them again later
grid_counter = length/len(grid)
#k-times: insert last item from list conv to beginning and than delete the last item
for i in range(k):
conv.insert(0, conv[(len(conv)-1)])
del conv[len(conv)-1]
#reconvert 1D list conv to a 2D list and return it
return [conv[i:i+grid_counter] for i in xrange(0, len(conv), grid_counter)]
如您所见,for 循环使用len(conv)-1 运行,我想替换它以节省运行时间。所以我在上面预先计算了它。
但是,一旦我用last 替换len(conv)-1,代码就不再起作用,因为它给出了错误的输出。所以我退后一步,只用length 替换了len(conv),但问题仍然存在。即使我在 for 循环中预先计算 last 和 length 也不起作用。
我有什么遗漏或做错了吗?
【问题讨论】:
标签: python python-2.7 for-loop replace