I don't think map()
is a good candidate for this problem because your desired result is nested rather than flattened. It'd be a little more verbose than just using a list comprehension to achieve your desired result. Here's a cleaner way of initializing B
.
B = np.array([np.min(A.T/r, axis=1) for r in A.T])
This iterates over every column of A
(every row of A.T
) and computes the broadcasted division A.T/r
. Numpy is able to optimize that far beyond what we can do with raw loops. Then the use of np.min()
computes minimums of that matrix we just computed along every row (rows instead of columns because of the parameter axis=1
) more quickly than we would be able to with the builtin min()
because of internal vectorization.
If you did want to map something, @MartijnPieters points out that you could use itertools with itertools.product(range(len(A[0])), repeat=2)
to achieve the same pairs of indices. Otherwise, you could use the generator ((r, s) for r in A.T for s in A.T)
to get pairs of rows instead of pairs of indices. In either case you could apply map()
across that iterable, but you'd still have to somehow nest the results to initalize B
properly.
Note: that this probably isn't the result you would expect. The elements of A
are integers by default (notice that you used, e.g., 3
instead of 3.
). When you divide the integer elements of A
you get integers again. In your code, that was partially obfuscated by the fact that np.zeros()
casts those integers to floats, but the math was wrong regardless. To fix that, pass an additional argument when constructing A
:
A = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]], float)