DEV Community

Nw3965
Nw3965

Posted on

Count negatives in grid

LeetCode

1st try.

class Solution:
    def countNegatives(self, grid: List[List[int]]) -> int:
        #Count negetive numbers.
        i = int<=-1
        negetive = count.List(i)
        return negetive
Enter fullscreen mode Exit fullscreen mode

2nd try with AI.

from typing import List

class Solution:
    def countNegatives(self, grid: List[List[int]]) -> int:
        # Count negative numbers.
        negative_count = 0

        for row in grid:
            for num in row:
                if num < 0:
                    negative_count += 1

        return negative_count
Enter fullscreen mode Exit fullscreen mode

What does this mean ?
for row in grid:
for num in row:

ChatGPT
for row in grid:
for num in row:
is a nested loop structure that iterates over each element in a 2D grid.

Here's a breakdown:

for row in grid:: This loop iterates over each row in the 2D grid. In each iteration, row represents a list of numbers (a row in the grid).

for num in row:: This inner loop iterates over each element (num) in the current row (row). In each iteration of the inner loop, num represents a specific number in the current row.

So, when you combine these loops, the entire structure iterates over each element in the 2D grid. This is commonly used to perform operations on each individual element or to extract information from the entire grid. In the context of your original code, it is used to count the number of negative numbers in the grid by checking each element (num) in each row (row).

Top comments (0)