list - Python: I don't understand the order of a function calling a function -
i'm following book data science scratch joel grus , decribe following code create identity matrix
def make_matrix(num_rows, num_cols, entry_fn): return [[entry_fn(i, j) j in range(num_cols)] in range(num_rows)] def is_diagonal(i, j): return 1 if == j else 0 identity_matrix = make_matrix(5, 5, is_diagonal)
although can sort of see how create identity matrix, i'm having difficulties understanding it.
the way see call function make_matrix
arguments 5
, 5
, is_diagonal
. @ point code go is_diagonal(i, j) j in range(5)
, go function is_diagonal
without having seen outer loop ... in range(5)
. if true, seems function is_diagonal
input variable (0,j)
, (1,j)
, ..., (4,j)
, is_diagonal
doesn't enough input variables (because j
isn't defined). please explain i'm going wrong in train of thoughts?
that type of expression (a comprehension) best of thought of in yoda sense: backwards is. last part of expression evaluated before first.
this function equivalent of:
def make_matrix(num_rows, num_cols, entry_fn): ret = [] # dealing outer list # , outer loop in range(num_rows): cur = [] # , inner list # , inner loop j in range(num_cols): curr.append(entry_fn(i,j)) # add result inner list # , once you're done inner loop, , result outer list ret.append(cur) # finally, complete outer loop , return result return ret
both i
and j
exist in greater context of function, though i
defined after j
in more compressed version.
Comments
Post a Comment