5.2. Array Sort

5.2.1. Rationale

5.2.2. SetUp

>>> import numpy as np

5.2.3. Sort

Sort vector:

>>> a = np.array([2, 3, 1])
>>> a.sort()
>>>
>>> a
array([1, 2, 3])

Sort matrix:

>>> a = np.array([[9, 7, 8],
...               [2, 3, 1],
...               [5, 6, 4]])
>>> a.sort()
>>> a
array([[7, 8, 9],
       [1, 2, 3],
       [4, 5, 6]])

Sort matrix rows:

>>> a = np.array([[9, 7, 8],
...               [2, 3, 1],
...               [5, 6, 4]])
>>>
>>> a.sort(axis=0)
>>> a
array([[2, 3, 1],
       [5, 6, 4],
       [9, 7, 8]])

Sort matrix columns:

>>> a = np.array([[9, 7, 8],
...               [2, 3, 1],
...               [5, 6, 4]])
>>>
>>> a.sort(axis=1)
>>> a
array([[7, 8, 9],
       [1, 2, 3],
       [4, 5, 6]])

5.2.4. Flip

  • Does not modify inplace

  • Returns new np.ndarray

  • Reverse the order of elements in an array along the given axis

Flip vector:

>>> a = np.array([1, 2, 3])
>>>
>>> np.flip(a)
array([3, 2, 1])

Flip matrix:

>>> a = np.array([[1, 2, 3],
...               [4, 5, 6]])

Flip matrix by crossline from top-left to bottom-right:

>>> np.flip(a)
array([[6, 5, 4],
       [3, 2, 1]])

Flip matrix by rows (bottom rows goes up, upper rows goes down):

>>> np.flip(a, axis=0)
array([[4, 5, 6],
       [1, 2, 3]])

Flip matrix by column (left columns from center goes right, right columns go left):

>>> np.flip(a, axis=1)
array([[3, 2, 1],
       [6, 5, 4]])

5.2.5. Assignments

Code 5.54. Solution
"""
* Assignment: Numpy Sort
* Complexity: easy
* Lines of code: 2 lines
* Time: 3 min

English:
    1. Define `result_sort` with sorted `DATA` by columns
    2. Define `result_flip` with flipped `DATA` by rows
    3. Run doctests - all must succeed

Polish:
    1. Zdefiniuj `result_sort` z posortowanym `DATA` po kolumnach
    2. Zdefiniuj `result_flip` z flipniętym `DATA` po wierszach
    3. Uruchom doctesty - wszystkie muszą się powieść

Hints:
    * `.sort()` returns `None`

Tests:
    >>> import sys; sys.tracebacklimit = 0

    >>> assert result_sort is not Ellipsis, \
    'Assign result to variable: `result_sort`'
    >>> assert type(result_sort) is np.ndarray, \
    'Variable `result_sort` has invalid type, expected: np.ndarray'

    >>> assert result_flip is not Ellipsis, \
    'Assign result to variable: `result_flip`'
    >>> assert type(result_flip) is np.ndarray, \
    'Variable `result_flip` has invalid type, expected: np.ndarray'

    >>> result_sort
    array([[44, 47, 64, 67],
           [ 9, 21, 67, 83],
           [36, 70, 87, 88]])

    >>> result_flip
    array([[36, 87, 70, 88],
           [67,  9, 83, 21],
           [44, 47, 64, 67]])
"""

import numpy as np


DATA = np.array([[44, 47, 64, 67],
                 [67,  9, 83, 21],
                 [36, 87, 70, 88]])

result_sort = ...
result_flip = ...