← All challenges
mediumsympy/sympy · v1.5

Lambdify misinterprets some matrix expressions

mathsymbolicbase f91de69558
Mode

60 minutes, the full token budget.

  • Time limit60 min
  • Token budgetup to 1M
  • Worth up to210 XP

Opens VS Code with an AI agent in a new tab. Prompts, tokens, tool calls and test runs are recorded and scored.

Problem statement

Using lambdify on an expression containing an identity matrix gives us an unexpected result:

python
>>> import numpy as np
>>> n = symbols('n', integer=True)
>>> A = MatrixSymbol("A", n, n)
>>> a = np.array([[1, 2], [3, 4]])
>>> f = lambdify(A, A + Identity(n))
>>> f(a)
array([[1.+1.j, 2.+1.j],
       [3.+1.j, 4.+1.j]])

Instead, the output should be array([[2, 2], [3, 5]]), since we're adding an identity matrix to the array. Inspecting the globals and source code of f shows us why we get the result:

python
>>> import inspect
>>> print(inspect.getsource(f))
def _lambdifygenerated(A):
    return (I + A)
>>> f.__globals__['I']
1j

The code printer prints I, which is currently being interpreted as a Python built-in complex number. The printer should support printing identity matrices, and signal an error for unsupported expressions that might be misinterpreted.

The environment starts at commit f91de695585c (sympy/sympy 1.5), dependencies installed and tests runnable from the first minute. You are graded by hidden tests taken from the fix that was actually merged upstream.