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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With