5 Best Ways to Print a Matrix in Snake Pattern Using Python

πŸ’‘ Problem Formulation: The task is to present a matrix in a manner that resembles a snake’s traversal – zigzagging from left to right in one row, and then right to left in the next row, and so on. Assume an input matrix like [[1, 2, 3], [4, 5, 6], [7, 8, 9]], the desired output would be a single sequence: [1, 2, 3, 6, 5, 4, 7, 8, 9], reflecting the snake pattern order.

Method 1: Using Simple Looping

The first method takes a traditional approach, iterating through each row and reversing the order of elements in alternate rows. This simple looping structure is easy to understand and implement but may not be optimized for very large matrices.

Here’s an example:

def print_snake_pattern(matrix):
    for i in range(len(matrix)):
        if i % 2 == 0:
            # Print left to right for even rows
            print(matrix[i])
        else:
            # Print right to left for odd rows
            print(matrix[i][::-1])

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print_snake_pattern(matrix)

Output:

[1, 2, 3]
[6, 5, 4]
[7, 8, 9]

This code snippet defines a function that accepts a matrix and iterates through each of its rows. For even-numbered rows, it prints elements left to right, and for odd-numbered rows, it prints elements from right to left, mimicking a snake-like pattern.

Method 2: Using List Comprehension

With Python’s list comprehension feature, we can condense the code required to print a matrix in a snake pattern. This method makes the code more concise and pythonic.

Here’s an example:

def snake_pattern_with_comprehension(matrix):
    return [elem for i, row in enumerate(matrix) for elem in (row if i % 2 == 0 else reversed(row))]

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(snake_pattern_with_comprehension(matrix))

Output:

[1, 2, 3, 6, 5, 4, 7, 8, 9]

This snippet leverages list comprehensions to iterate over rows of the matrix, reversing the order of the elements in every odd-indexed row. This creates a flattened list that represents the matrix in a snake pattern.

Method 3: Functional Approach with Map and Lambda

This method utilizes the power of Python’s functional programming features, like map and lambda, to apply a function that reverses odd-indexed rows of the matrix in situ.

Here’s an example:

def snake_pattern_functional(matrix):
    return [elem for row in map(lambda x: x if x[1] % 2 == 0 else x[0][::-1], enumerate(matrix)) for elem in row]

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(snake_pattern_functional(matrix))

Output:

[1, 2, 3, 6, 5, 4, 7, 8, 9]

This functional one-liner uses map to apply a function over the enumerated matrix, reversing the list on odd rows. The returned map object is then flattened into a list using list comprehension.

Method 4: Using NumPy for Large Matrices

For those working with large datasets, NumPy offers efficient array operations. This method leverages NumPy’s slicing capabilities to handle large matrices more efficiently than native Python structures.

Here’s an example:

import numpy as np

def print_snake_pattern_numpy(matrix):
    snake_pattern = np.empty(0)
    for i in range(len(matrix)):
        snake_pattern = np.concatenate((snake_pattern, matrix[i, ::-1] if i % 2 else matrix[i]))
    return snake_pattern

matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(print_snake_pattern_numpy(matrix))

Output:

[1. 2. 3. 6. 5. 4. 7. 8. 9.]

Here, the NumPy library’s array and concatenation functions are used to generate the snake pattern. Each row of the matrix is appended to an empty array, reversing every odd row before the concatenation.

Bonus One-Liner Method 5: Advanced List Comprehension

This method combines several Python list comprehension tricks to achieve the snake pattern printing in a single line. It’s most suitable for Pythonists who adore code brevity.

Here’s an example:

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print([cell for idx, row in enumerate(matrix) for cell in (row[::-1] if idx % 2 else row)])

Output:

[1, 2, 3, 6, 5, 4, 7, 8, 9]

This code uses advanced list comprehension to iterate over each row and its index. It accounts for the row index to determine when to reverse the row. The entire operation is condensed into a single readable line.

Summary/Discussion

  • Method 1: Simple Looping. It’s very straightforward and easy to understand. However, it may not be the most efficient for large matrices.
  • Method 2: List Comprehension. More pythonic and concise compared to looping, making the code more readable and potentially more performant.
  • Method 3: Functional Approach. Utilizes powerful functional programming concepts for elegance and potentially better performance with the right optimizations.
  • Method 4: Using NumPy. This method is highly efficient for large matrices, leveraging the optimized performance of NumPy, but it does introduce a dependency on an external library.
  • Method 5: Advanced One-Liner. Demonstrates Python’s ability to perform complex tasks in a single line, showing the flexibility of list comprehensions. It may come at a cost of readability for some users.