假设我们有以下列表
mag = [ [0, 1, 1, 1], [0, 1, 0, 1], [1, 1, 0, 1], [0, 1, 0, 1], ]
问题:需要添加或合并新行,例如 [1, 0, 0, 1]
.
规则:如果我添加与某些行重叠的列表,则应根据哪个项目与所提供的项目重叠来附加或合并该列表。
示例(开头的 mag 矩阵):
mag.add([0, 0, 1, 0]) [ [0, 1, 1, 1], # << -- here is were overlapped [0, 1, 1, 1], # << -- here will be merged [1, 1, 0, 1], [0, 1, 0, 1], ]
示例 2(开头的 mag 矩阵):
mag.add([0, 1, 0, 0]) [ [0, 1, 1, 1], [0, 1, 0, 1], [1, 1, 0, 1], [0, 1, 0, 1], # << -- overlaps first list from end, will be appended [0, 1, 0, 0], ]
示例 3(开头的 mag 矩阵):
mag.add([1, 0, 0, 0]) [ [0, 1, 1, 1], [0, 1, 0, 1], [1, 1, 0, 1], # << -- overlaps here [1, 1, 0, 1], # << -- here were merged ]
更清楚地说,假设这是俄罗斯方 block ,其中新列表如 [0, 1, 0, 1]
是一个数字,其中 1
是一个 block 并且 0
是一个自由空间。我们需要了解如果图形从底部移动到顶部,它可能会在哪里。
最佳答案
这里我们从末尾开始循环遍历矩阵,检查每一行是否重叠。如果是,我们编辑上一行。如果它到达矩阵的顶部,我们合并顶行。
def overlap(a, b):
return any(x&y for x, y in zip(a, b))
def merge(a, b):
return [x|y for x, y in zip(a, b)]
def update_matrix(mat, row):
if overlap(mat[-1], row): # If the new row doesn't fit at all, add it at the end
mat.append(row)
return
for ind, line in enumerate(reversed(mat)):
if overlap(line, row):
change_index = ~(ind-1) # This trick uses negative indexing to index
# from the end of the list
break # We have the row to merge
else:
change_index = 0 # We got to the top, so we need to change the first row
mat[change_index] = merge(mat[change_index], row)
关于python - 修改矩阵。 python 非常有趣的任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55123268/