Python 中的 Boss Fight
pythonserver side programmingprogramming更新于 2025/11/3 19:56:17
假设我们有一个名为 fighters 的二进制列表和另一个名为 bosses 的二进制列表列表。在 fighters 列表中,1 代表一名 fighter。同样,在 bosses 列表中,1 代表一名 Boss。如果 Boss 所在行包含的 fighters 数量多于 Boss 数量,则 fighters 可以击败该 Boss。我们必须返回一个新的 Boss 矩阵,其中删除了被击败的 Boss 行。
因此,如果输入为 fighters = [0,1,1]
| 0 | 1 | 1 |
| 0 | 0 | 0 |
| 0 | 0 | 1 |
| 0 | 1 | |
| 1 | 1 |
则输出为
| 0 | 1 | 1 |
| 1 | 1 |
为了解决这个问题,我们将遵循以下步骤 −
fighter_cnt := fighters 所有元素的总和
result := a new list
对于 bosses 中的每一行,执行
如果 fighter_cnt <= row 中每个元素的总和,则
在结果末尾插入行
返回结果
让我们看看下面的实现,以便更好地理解 −
示例
class Solution: def solve(self, fighters, bosses): fighter_cnt = sum(fighters) result = [] for row in bosses: if fighter_cnt <= sum(row): result.append(row) return result ob = Solution() fighters = [0, 1, 1] bosses = [[0, 0, 0], [0, 0, 1], [0, 1, 1], [1, 1, 1]] print(ob.solve(fighters, bosses))
输入
[0, 1, 1], [[0, 0, 0], [0, 0, 1], [0, 1, 1], [1, 1, 1]]
输出
[[0, 1, 1], [1, 1, 1]]
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

