How about:
>>> imatrix = lambda n: [[1 if j == i else 0 for j in range(n)] for i in range(n)]
>>> imatrix(3)
[[1, 0, 0], [0, 1, 0], [0, 0, 1]]
1 if j == i else 0
is an example of Python's conditional expression.
Question
I just tried to learn both list comprehensions and Lambda functions. I think I understand the concept but I have been given a task to create a program that when fed in a positive integer creates the identity matrix. Basically if I fed in 2 it would give me: [[1, 0],[0, 1]] and if I gave it 3: [[1, 0, 0],[0, 1, 0], [0, 0, 1] so list within a list.
Now I need to create this all within a lambda function. So that if I type:
FUNCTIONNAME(x) it will retrieve the identity matrix of size x-by-x.
By the way x will always be a positive integer.
This is what I have so far:
FUNCTIONNAME = lambda x: ##insertCodeHere## for i in range(1, x)
I think I am doing it right but I don't know. If anyone has an idea please help!
Solution
How about:
>>> imatrix = lambda n: [[1 if j == i else 0 for j in range(n)] for i in range(n)]
>>> imatrix(3)
[[1, 0, 0], [0, 1, 0], [0, 0, 1]]
1 if j == i else 0
is an example of Python's conditional expression.
OTHER TIPS
This would be my favorite way to do it:
identity = lambda x: [[int(i==j) for i in range(x)] for j in range(x)]
It takes advantage of the fact that True
maps to 1 and False
maps to 0.
Just for completeness (and to highlight how one really should be doing numerical stuff in python):
import numpy
list_eye = lambda n: numpy.eye(n).tolist()
Of course, in practice you'd probably just be using eye(n)
by itself and be working with the numpy arrays.