How to find the N smallest values in a 2D list in Python

1 Answer

0 votes
import heapq

"""
    Find the N smallest values in a 2D array.

    Approach:
    1. Flatten the 2D array into a single list.
    2. Use heapq.nsmallest, which efficiently extracts the smallest N values
       without sorting the entire dataset.
    3. Print the result.

    This keeps the code expressive and efficient while relying on
    Python's built‑in algorithms.
"""

def flatten(matrix):
    """Flatten a 2D list into a 1D list."""
    return [value for row in matrix for value in row]


def smallest_n(matrix, n):
    """Return the N smallest values using an efficient heap-based selection."""
    flat = flatten(matrix)
    
    return heapq.nsmallest(n, flat)


def main():
    matrix = [
        [42, 12, 85,  3],
        [ 7, 99, 15, 23],
        [64,  1, 18, 30],
        [ 3, 55, 11, 90]
    ]

    n = 5

    values = smallest_n(matrix, n)

    print(f"The {n} smallest values:")
    print(*values)


if __name__ == "__main__":
    main()


"""
run:

The 5 smallest values:
1 3 3 7 11

"""

 



answered Aug 10 by avibootz
...