Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Lambda Identity Matrix

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!

like image 366
NoviceProgrammer Avatar asked Aug 15 '13 08:08

NoviceProgrammer


1 Answers

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.

like image 167
codeape Avatar answered Sep 27 '22 22:09

codeape