pythonadvanced15 minutes

Fix Bug in Efficient Large-Scale Matrix Multiplication

Identify and fix a subtle bug in an optimized Python function designed to multiply large matrices efficiently using NumPy, without changing overall approach or reducing performance.

Challenge prompt

The function below is intended to efficiently multiply two large matrices leveraging NumPy. However, the results it produces are incorrect for some inputs. Your task is to find and fix the bug causing the incorrect output, ensuring the function maintains high performance and handles large inputs correctly. Do not completely rewrite the algorithm; focus on debugging the existing approach.

Guidance

  • Carefully check the assumptions about the shape and dimensions of the matrices before multiplication.
  • Review how you are using NumPy array operations and broadcasting rules that might affect matrix multiplication.
  • Validate the result by comparing it against NumPy's built-in matrix multiplication for correctness.

Hints

  • Check if you are properly using the '@' operator or numpy.dot for multiplying matrices.
  • Look closely at how inputs are converted or reshaped prior to operation.
  • Remember that matrix multiplication requires the inner dimensions of the two matrices to match.

Starter code

import numpy as np

def fast_matrix_multiply(A, B):
    # Intended to multiply two matrices A and B
    # BUG: sometimes gives incorrect result or errors with large inputs
    A = np.array(A)
    B = np.array(B)
    result = A * B  # Attempt to multiply matrices element-wise (bug here)
    return result

# Example test case
A = np.arange(12).reshape(3,4)
B = np.arange(8).reshape(4,2)
print(fast_matrix_multiply(A, B))

Expected output

[[ 28 31] [ 76 89] [124 147]]

Core concepts

matrix multiplicationnumpy operationsdebuggingarray broadcasting

Challenge a Friend

Send this duel to someone else and see if they can solve it.