adding a simpler solution to 'sum over last two axes' exercise'

This commit is contained in:
ibah 2016-09-27 15:16:26 +02:00
parent 15ede08113
commit b74eeca0cf
2 changed files with 10 additions and 0 deletions

View File

@ -1436,6 +1436,11 @@
"outputs": [], "outputs": [],
"source": [ "source": [
"A = np.random.randint(0,10,(3,4,3,4))\n", "A = np.random.randint(0,10,(3,4,3,4))\n",
"# solution by passing a tuple of axes\n",
"sum = A.sum(axis=(-2,-1))\n",
"print(sum)\n",
"# solution by flattening the last two dimensions into one\n",
"# (useful for functions that don't accept tuples for axis argument)\n",
"sum = A.reshape(A.shape[:-2] + (-1,)).sum(axis=-1)\n", "sum = A.reshape(A.shape[:-2] + (-1,)).sum(axis=-1)\n",
"print(sum)" "print(sum)"
] ]

View File

@ -693,6 +693,11 @@ print(np.unique(I))
```python ```python
A = np.random.randint(0,10,(3,4,3,4)) A = np.random.randint(0,10,(3,4,3,4))
# solution by passing a tuple of axes
sum = A.sum(axis=(-2,-1))
print(sum)
# solution by flattening the last two dimensions into one
# (useful for functions that don't accept tuples for axis argument)
sum = A.reshape(A.shape[:-2] + (-1,)).sum(axis=-1) sum = A.reshape(A.shape[:-2] + (-1,)).sum(axis=-1)
print(sum) print(sum)
``` ```