python - 修改矩阵。 python 非常有趣的任务

标签 python arrays list matrix

假设我们有以下列表

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/

相关文章:

Java如何返回一个斐波那契值从1开始的数组?

ios - 表格 View 中的缓慢/断断续续的滚动

Python 列表问题

python - Pygubu 从 UI 文件加载新窗口

c - 如何初始化一个长度不固定的数组?

python - 如何从 Python 中的一组列表中找到最长的匹配项?

java - 如何在 Java 中使用 Comparables 创建自定义参数化列表对象?

Python合并不同长度列表的列表

不使用随机模块的Python随机函数

python - Plotly Express 散点图不会绘制 x 变量的完整范围