CPDS in Python Lab - Introduction to Packages and NumPy

1. Why do we need Python packages?

A module is a single Python file containing reusable variables, functions or classes.

A package is a collection of related modules that provides tools for a particular type of work.

Instead of writing every numerical algorithm ourselves, we can use packages containing functions that are already implemented and tested.

Examples:

Package Main use
NumPy Numerical arrays and computations
Matplotlib Plotting and visualization
Pandas Data analysis
SciPy Scientific computing
Scikit-learn Machine learning

Question 1

Suppose we want to calculate the square root of 25. Can Python already provide a function for this instead of us writing the algorithm ourselves?

sqrt(25)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
/tmp/ipykernel_1328/3140457483.py in <cell line: 0>()
----> 1 sqrt(25)

NameError: name 'sqrt' is not defined
25**(1/2)
5.0
pow(25,1/2)
5.0
import math
math.log(25,10)
1.3979400086720375
import numpy
numpy.sqrt(25)
np.float64(5.0)

The sqrt() function already exists inside the math module.

2. How do we import a package?

Before using a package, Python must know that we want to use it.

The general syntax is:

import package_name

For scientific computing, NumPy is normally imported as

import numpy as np

Here, np is simply a short alias for numpy.

Question 2

Import NumPy using the standard alias np and check the installed NumPy version.

import numpy as np
np.sqrt(25)
np.float64(5.0)
numpy.__version__
'2.1.3'
np.__version__
'2.1.3'

deprecated

3. What is a NumPy array?

The main object in NumPy is the ndarray, or N-dimensional array.

A Python list may contain general objects, but a NumPy array is optimized for storing and processing numerical data efficiently.

Question 3

Create the vector

$ x = \[\begin{bmatrix} 2 & 4 & 6 & 8 & 10 \end{bmatrix}\]

$

as a NumPy array.

x = [2,3,4,5,6,7]
np.array(x)
array([2, 3, 4, 5, 6, 7])
numpy.array(x)
array([2, 3, 4, 5, 6, 7])
x
[2, 3, 4, 5, 6, 7]
x = numpy.array(x)
x
array([2, 3, 4, 5, 6, 7])
[1,2,3]*2
[1, 2, 3, 1, 2, 3]
for i in [1,2,3]*20:
  print(i**2)
1
4
9
1
4
9
1
4
9
1
4
9
1
4
9
1
4
9
1
4
9
1
4
9
1
4
9
1
4
9
1
4
9
1
4
9
1
4
9
1
4
9
1
4
9
1
4
9
1
4
9
1
4
9
1
4
9
1
4
9
np.array([1,2,3])**2
array([1, 4, 9])

Question 4

Can NumPy also represent a matrix?

$ A = \[\begin{bmatrix} 1 & 2 & 3\\ 4 & 5 & 6\\ 7 & 8 & 9 \end{bmatrix}\]

. $

A = [[1,2,3],[2,3,4]]
A = np.array([[[1,2,3],[1,2,3]],[[1,2,3],[1,2,3]]])
A
array([[[1, 2, 3],
        [1, 2, 3]],

       [[1, 2, 3],
        [1, 2, 3]]])
A = np.array(A)
A
array([[1, 2, 3],
       [2, 3, 4]])
A**2
array([[ 1,  4,  9],
       [ 4,  9, 16]])

4. Create NumPy arrays automatically?

Question 5

Create:

  1. a (2 x 3) matrix of zeros,
  2. a (2 x 3) matrix of ones.
[[0,0,0],[0,0,0]]
[[0, 0, 0], [0, 0, 0]]
np.array([[0,0,0],[0,0,0]])
array([[0, 0, 0],
       [0, 0, 0]])
[[0]*3,[0,0,0]]
[[0, 0, 0], [0, 0, 0]]
np.array([[0]*3,[0,0,0]])
array([[0, 0, 0],
       [0, 0, 0]])
np.zeros((2,3))
array([[0., 0., 0.],
       [0., 0., 0.]])
np.ones((2,3))
array([[1., 1., 1.],
       [1., 1., 1.]])

Useful NumPy functions include:

  • np.zeros(shape) — creates an array filled with zeros,
  • np.ones(shape) — creates an array filled with ones,
  • np.arange(start, stop, step) — creates regularly spaced values using a step size,
  • np.linspace(start, stop, number) — creates a specified number of equally spaced values.

Question 6

Generate the numbers

[ 0,2,4,6,8 ]

using arange().

np.arange(1,11)
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10])
np.arange(1,11,1)
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10])
np.arange(0,10,2)
array([0, 2, 4, 6, 8])
np.linspace(1,11,10)
array([ 1.        ,  2.11111111,  3.22222222,  4.33333333,  5.44444444,
        6.55555556,  7.66666667,  8.77777778,  9.88888889, 11.        ])
for i in range(-10,0,2):
  print(i)
-10
-8
-6
-4
-2

In arange(start, stop, step).

Question 7

For a simulation from (t=0) to (t=10) seconds, generate exactly 11 equally spaced time points.

np.linspace(0,10,11)
array([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10.])

Question 8

For the matrix

$ A = \[\begin{bmatrix} 10 & 20 & 30\\ 40 & 50 & 60 \end{bmatrix}\]

, $

find its shape, number of dimensions, total number of elements and data type.

A = np.array([[10,20,30],[40,50,60]])
A.shape
(2, 3)
A.ndim
2
len(A)
2
A.elements
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
/tmp/ipykernel_1328/4048500941.py in <cell line: 0>()
----> 1 A.elements

AttributeError: 'numpy.ndarray' object has no attribute 'elements'
A.size
6
A = [[10,20,30],
    [40,50,60],
     [40,50,60],
     [40,50,60],
     [40,50,60],
     [40,50,60]]
len(A[0])+len(A[1])
6
A = np.array(A)
A.size
18
type(A)
numpy.ndarray
  • shape — dimensions of the array,
  • ndim — number of dimensions,
  • size — total number of elements,
  • dtype — data type of the elements.

6. Access elements of a NumPy array

Question 9

Using the matrix below:

  1. print the element in the first row and second column,
  2. print the entire second row,
  3. print the entire third column.
[1,0,2]
[1, 0, 2]
[1,0,2][1]
0
[1,0,2][2]
2
[1,0,2][-2]
0
np.array([1,0,2])
array([1, 0, 2])
np.array([1,0,2]).shape
(3,)
np.array([1,0,2])[0]
np.int64(1)

int32, int64, float32, float64

np.array([1,0,2],dtype=numpy.int32)[0]
np.int32(1)
np.array([1,0,2],dtype=numpy.float32)[0]
np.float32(1.0)
[[1,2],[2,3]][1]
[2, 3]
[[1,2],[2,3]][1][1]
3
np.array([[1,2],[2,3]])[1,1]
np.int64(3)
np.array([[1,2],[2,3]])[1:]
array([[2, 3]])

NumPy uses zero-based indexing, like Python lists.

For a one-dimensional array:

x[0]

is the first element.

For a two-dimensional array:

A[row, column]

selects an element.

The symbol : means take all entries along that direction.

Therefore:

A[1, :]

means: second row, all columns.

and

A[:, 2]

means: all rows, third column.

7. Arithmetic with NumPy arrays

One of the biggest advantages of NumPy is that arithmetic can be performed on entire arrays directly.

This is called vectorization.

Instead of processing each element manually with a loop, NumPy applies the operation to the complete array.

Question 10

Let

\(x = [1,2,3,4].\)

Find:

  1. \(2x\),
  2. \(x+10\),
  3. \(x^2\).
[1,2,3,4]+[4,5,6,7]
[1, 2, 3, 4, 4, 5, 6, 7]
[1,2,3,4]**2
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/tmp/ipykernel_1328/1825985778.py in <cell line: 0>()
----> 1 [1,2,3,4]**2

TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'int'
np.array([1,2,3,4]) + np.array([4,5,6,7])
array([ 5,  7,  9, 11])
3*np.array([1,2,3,4])
array([ 3,  6,  9, 12])
np.array([1,2,3,4]) + 10
array([11, 12, 13, 14])

8. Element-wise operations versus matrix multiplication

Question 11

Compare A * B and A @ B for the matrices below.

A = np.array([[1,2,3],[3,4,5]])
B = np.array([[1,2,3],[3,4,5]])
A *B
array([[ 1,  4,  9],
       [ 9, 16, 25]])
A @B
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/tmp/ipykernel_1328/2343860730.py in <cell line: 0>()
----> 1 A @B

ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?) (size 2 is different from 3)
np.transpose(A)
array([[1, 3],
       [2, 4],
       [3, 5]])
A.T
array([[1, 3],
       [2, 4],
       [3, 5]])
A.T * B
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/tmp/ipykernel_1328/3887616290.py in <cell line: 0>()
----> 1 A.T * B

ValueError: operands could not be broadcast together with shapes (3,2) (2,3) 
A.T @ B
array([[10, 14, 18],
       [14, 20, 26],
       [18, 26, 34]])
np.matmul(A.T,B)
array([[10, 14, 18],
       [14, 20, 26],
       [18, 26, 34]])
np.array(np.dot(np.array([1,2,3]),np.array([2,3,4])),dtype = numpy.float32)
array(20., dtype=float32)

For NumPy arrays:

A * B

performs element-wise multiplication.

For matrices:

A @ B

performs matrix multiplication.

These are different operations.

9. Can NumPy apply mathematical functions to a complete array?

NumPy provides vectorized mathematical functions.

Some

  • np.sqrt(x) — square root,
  • np.exp(x) — exponential,
  • np.log(x) — natural logarithm,
  • np.sin(x) — sine,
  • np.cos(x) — cosine,
  • np.abs(x) — absolute value.

Question 12

For

\(x=[1,4,9,16,25],\)

calculate the square root of every element using one command.

import numpy as np
x = [1,4,9,16,25]
x = np.array(x)
np.sqrt(x)
array([1., 2., 3., 4., 5.])
np.sin(x)
array([ 0.84147098, -0.7568025 ,  0.41211849, -0.28790332, -0.13235175])
np.cos(x)
array([ 0.54030231, -0.65364362, -0.91113026, -0.95765948,  0.99120281])

10. Basic statistical functions

  • np.sum(x) — sum,
  • np.mean(x) — arithmetic mean,
  • np.median(x) — median,
  • np.std(x) — standard deviation,
  • np.min(x) — minimum,
  • np.max(x) — maximum.

(These are only some of the functions not all)

Question 13

The temperatures measured during five experiments are

\([28.5,30.0,29.5,31.0,27.5].\)

Find the mean, minimum and maximum temperatures.

x
array([ 1,  4,  9, 16, 25])
np.min(x)
np.int64(1)
np.max(x)
np.int64(25)
np.mean(x)
np.float64(11.0)

A vehicle travels with the following measured velocities in m/s:

\(v=[0,5,10,15,20,25].\)

Question 14

Using NumPy:

  1. create the velocity array,

  2. convert every velocity from m/s to km/h using

    $ v_{{km/h}}=3.6v_{{m/s}}, $

  3. find the average velocity in km/h,

  4. find the largest velocity in km/h.

Try the question first before running the solution.

v = [0,5,10,15,20,25]
v = np.array(v)
v
array([ 0,  5, 10, 15, 20, 25])
np.v*3.6
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
/tmp/ipykernel_840/4118434146.py in <cell line: 0>()
----> 1 np.v*3.6

/usr/local/lib/python3.13/dist-packages/numpy/__init__.py in __getattr__(attr)
    412             return char.chararray
    413 
--> 414         raise AttributeError("module {!r} has no attribute "
    415                              "{!r}".format(__name__, attr))
    416 

AttributeError: module 'numpy' has no attribute 'v'
v_kmh = v*3.6
np.mean(v_kmh)
np.float64(45.0)
np.max(v_kmh)
np.float64(90.0)

Slicing a One-Dimensional Array

Slicing means selecting a part of an array.

The general form is

A[start:stop:step]

Question 15

From the array

\(A=[10,20,30,40,50,60,70],\)

extract the elements 20, 30, 40, 50.

A = np.array([10,20,30,40,50,60,70])
A[1:5]
array([20, 30, 40, 50])
A[-3:-7]
array([], dtype=int64)
A[-7:-2]
array([10, 20, 30, 40, 50])
A[:-2]
array([10, 20, 30, 40, 50])

Question 16

Using the same array:

  1. extract the first four elements,
  2. extract all elements from index 3 onward,
  3. extract every second element.
A[0:5]
array([10, 20, 30, 40, 50])
A[:5]
array([10, 20, 30, 40, 50])
A[0:7:2]
array([10, 30, 50, 70])
A[::2]
array([10, 30, 50, 70])

slicing a Two-Dimensional Array

For a matrix,

A[rows, columns]

can be used to select a block of entries.

Question 17

Given

$ A= \[\begin{bmatrix} 1&2&3&4\\ 5&6&7&8\\ 9&10&11&12 \end{bmatrix}\]

, $

extract the first two rows and the middle two columns.

A =  np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
A
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12]])
A[1:1]
array([], shape=(0, 4), dtype=int64)
A[1][1]
np.int64(6)
A[1,1]
np.int64(6)
A[1]
array([5, 6, 7, 8])
A[0:2]
array([[1, 2, 3, 4],
       [5, 6, 7, 8]])
A[:-2]
array([[1, 2, 3, 4]])
A[:-3]
array([], shape=(0, 4), dtype=int64)
A[-3:-1]
array([[1, 2, 3, 4],
       [5, 6, 7, 8]])
A[1:3]
array([[ 5,  6,  7,  8],
       [ 9, 10, 11, 12]])
A[1:]
array([[ 5,  6,  7,  8],
       [ 9, 10, 11, 12]])
A[0,0:2]
array([1, 2])

Reshaping an Array

Question 18

Create the numbers 1 to 12 and reshape them into a (3) matrix.

np.ones(12)
array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])
np.ones(12).reshape(3,4)
array([[1., 1., 1., 1.],
       [1., 1., 1., 1.],
       [1., 1., 1., 1.]])
np.ones(12).reshape(3,4).T
array([[1., 1., 1.],
       [1., 1., 1.],
       [1., 1., 1.],
       [1., 1., 1.]])
np.ones(12).reshape(3,4).flatten()
array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])

The function

A.reshape(new_shape)

changes the shape while preserving the elements.

Question 19

Can the same 12 elements be arranged as a (4 x 3) matrix?

Flattening an Array

Question 20

Convert the following matrix into a one-dimensional array.

A multidimensional array can be converted into a one-dimensional array using

A.flatten()

Transpose of a Matrix

Question 21

Find the transpose of a (2 x 3) matrix and compare the shapes before and after transposition.

A
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12]])
A.T
array([[ 1,  5,  9],
       [ 2,  6, 10],
       [ 3,  7, 11],
       [ 4,  8, 12]])
np.transpose(A)
array([[ 1,  5,  9],
       [ 2,  6, 10],
       [ 3,  7, 11],
       [ 4,  8, 12]])
np.reshape(A.flatten(), (3,4))
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12]])
A.flatten(0)A
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/tmp/ipykernel_840/4181211480.py in <cell line: 0>()
----> 1 A.flatten(0)

TypeError: order must be str, not int
A
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12]])
A.flatten(order = 'F')
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
/tmp/ipykernel_1350/3814642962.py in <cell line: 0>()
----> 1 A.flatten(order = 'F')

NameError: name 'A' is not defined

Element-wise Array Operations

Question 22

For

\(A=[10,20,30],\qquad B=[2,4,5],\)

find:

  1. (A+B),
  2. (A-B),
  3. (AB) element by element,
  4. (A/B) element by element.
B = A
A,B
(array([[ 1,  2,  3,  4],
        [ 5,  6,  7,  8],
        [ 9, 10, 11, 12]]),
 array([[ 1,  2,  3,  4],
        [ 5,  6,  7,  8],
        [ 9, 10, 11, 12]]))
A+B
array([[ 2,  4,  6,  8],
       [10, 12, 14, 16],
       [18, 20, 22, 24]])
A@B
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/tmp/ipykernel_840/2301120001.py in <cell line: 0>()
----> 1 A@B

ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?) (size 3 is different from 4)
A*B
array([[  1,   4,   9,  16],
       [ 25,  36,  49,  64],
       [ 81, 100, 121, 144]])
A/B
array([[1., 1., 1., 1.],
       [1., 1., 1., 1.],
       [1., 1., 1., 1.]])

Dot Product

Question 23

Calculate

\([1,2,3]\cdot[4,5,6].\)

np.dot(np.array([1,2,3]),
       np.array([4,5,6]))
np.int64(32)

Broadcasting

For example, adding

\([10,20,30]\)

to every row of

\(\begin{bmatrix} 1&2&3\\ 4&5&6 \end{bmatrix}\)

does not require a loop.

Question 24

Add the vector [10, 20, 30] to every row of the matrix.

[10,10] +10
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/tmp/ipykernel_840/456880799.py in <cell line: 0>()
----> 1 [10,10] +10

TypeError: can only concatenate list (not "int") to list
np.array([10,10]) +10
array([20, 20])
A + np.array([10,20,30,40])
array([[11, 22, 33, 44],
       [15, 26, 37, 48],
       [19, 30, 41, 52]])

Exponential and Natural Logarithm

Question 25

Evaluate \(e^x\) for \(x=0,1,2\).

np.exp(np.array([0,1,2]))
array([1.        , 2.71828183, 7.3890561 ])
np.log(np.array([6,1,2]),10)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/tmp/ipykernel_840/383732492.py in <cell line: 0>()
----> 1 np.log(np.array([6,1,2]),10)

TypeError: return arrays must be of ArrayType
np.log10(np.array([6,1,2]))
array([0.77815125, 0.        , 0.30103   ])
import math

math.log(10,5)
1.4306765580733933
np.emath.logn(10,5)
np.float64(0.6989700043360187)

Trigonometric Functions

Question 26

Generate five equally spaced angles from \(0\) to \(\pi\) and calculate their sine and cosine.

import numpy as np
np.linspace(0,np.pi,5)
array([0.        , 0.78539816, 1.57079633, 2.35619449, 3.14159265])
np.sin(np.linspace(0,np.pi,5))
array([0.00000000e+00, 7.07106781e-01, 1.00000000e+00, 7.07106781e-01,
       1.22464680e-16])

Question 27

Find the absolute values of

$ [-4,-2,3,-8]. $

np.abs(np.array([-1,-2,3]))
array([1, 2, 3])

Location of Maximum and Minimum

Question 28

For

$ A=[15,8,30,22,10], $

find:

  1. the maximum value,
  2. its index,
  3. the minimum value,
  4. its index.
np.max(np.array([15,8,30,22]))
np.int64(30)
np.argmin(np.array([15,8,30,22]))
np.int64(1)
np.argmax(np.array([15,8]))
np.int64(0)

Cumulative Sum

Question 29

Use np.cumsum() to calculate the cumulative sum.

np.cumsum(np.array([1,2,2,3,4]))
array([ 1,  3,  5,  8, 12])

Computation Along Rows and Columns

Question 30

For

$ A= \[\begin{bmatrix} 10&20&30\\ 40&50&60 \end{bmatrix}\]

, $

find:

  1. the sum of each column,
  2. the sum of each row,
  3. the mean of each column.
A = np.array([[10,20,30],[40,50,60]])
np.sum(A)
np.int64(210)
np.sum(A[1:])
np.int64(150)
np.sum(A[2:])
np.int64(0)
np.sum(A, axis=1)
array([ 60, 150])
np.mean(A, axis=0)
array([25., 35., 45.])

Boolean Conditions

Question 31

For

$ A=[12,5,18,7,25,3], $

check which elements are greater than 10.

14>=3
True
np.array([12,35,18,7,25])>=10
array([ True,  True,  True, False,  True])
np.array([12,35,18,7,25])[np.array([12,35,18,7,25])>=10]
array([12, 35, 18, 25])

Combining Arrays

Question 32

Combine

$ A=[1,2,3] $

and

$ B=[4,5,6]. $

[1,2,3]+[2,3,4]
[1, 2, 3, 2, 3, 4]
np.concatenate((np.array([1,2,3]),np.array([2,3,4])))
array([1, 2, 3, 2, 3, 4])

Suppose the displacement of an oscillator is

\(x(t)=2\sin(t).\)

We want to evaluate this function at several time points.

Question 33

Generate 9 equally spaced points between (0) and (2), and calculate

$ x(t)=2(t) $

without using a loop.

t = np.linspace(0,2*np.pi,9)
x_t = 2*np.sin(t)
x_t
array([ 0.00000000e+00,  1.41421356e+00,  2.00000000e+00,  1.41421356e+00,
        2.44929360e-16, -1.41421356e+00, -2.00000000e+00, -1.41421356e+00,
       -4.89858720e-16])

Experimental Temperature Data

The temperatures measured at eight time instants are

$ T=[25.0,26.5,28.0,29.2,30.1,29.8,28.7,27.5]. $

Question 34

Using NumPy:

  1. store the measurements in an array,
  2. find the mean temperature,
  3. find the maximum temperature,
  4. determine the index at which the maximum occurs,
  5. extract all temperatures greater than the mean,
  6. calculate the cumulative sum.
T = [1,2,3,4,5,6,7,8,9]
T = np.array(T)
np.mean(T)
np.float64(5.0)
np.max(T)
np.int64(9)
np.argmax(T)
np.int64(8)
T >np.mean(T)
array([False, False, False, False, False,  True,  True,  True,  True])
T[T >np.mean(T)]
array([6, 7, 8, 9])
np.cumsum(T)
array([ 1,  3,  6, 10, 15, 21, 28, 36, 45])

Motion Data

A moving object’s position is measured at equally spaced times:

\(x=[0,1.2,2.8,4.9,7.5,10.6].\)

The time points are

\(t=[0,1,2,3,4,5].\)

Question 35

Using NumPy:

  1. create t,
  2. store the position data,
  3. calculate the displacement between consecutive measurements using
  4. calculate the average position,
  5. determine the maximum position,
  6. determine when the maximum position occurs.
t = np.array([0,1,2,3,4,5])
np.arange(0,6,1)
array([0, 1, 2, 3, 4, 5])
x = np.array([0,3,4,5,6,6,3,2])
x[1:]-x[:-1]
array([ 3,  1,  1,  1,  0, -3, -1])

Creating arrays

np.array(...)
np.zeros(...)
np.ones(...)
np.arange(...)
np.linspace(...)

Array information

A.shape
A.ndim
A.size
A.dtype

Selecting and reshaping

A[index]
A[start:stop]
A[row, column]
A.reshape(...)
A.flatten()
A.T

Arithmetic and linear algebra

A + B
A - B
A * B
A / B
A @ B
np.dot(A, B)

Mathematical functions

np.sqrt(A)
np.exp(A)
np.log(A)
np.sin(A)
np.cos(A)
np.tan(A)
np.abs(A)

Statistical functions

np.sum(A)
np.mean(A)
np.median(A)
np.std(A)
np.var(A)
np.max(A)
np.min(A)
np.argmax(A)
np.argmin(A)
np.cumsum(A)

Filtering

A[A > value]

Question 1 - Number Analysis

Write a Python program that accepts a positive integer and finds:

  1. the number of digits,
  2. the sum of its digits,
  3. the largest digit,
  4. the smallest digit.

Example

Input: 58327

Number of digits = 5
Sum of digits = 25
Largest digit = 8
Smallest digit = 2
inp = input("give num")
give num16354
type(inp)
str
list(inp)
['1', '6', '3', '5', '4']
inp
'16354'
[int(inp)]
[16354]
np.array(list(inp))
array(['1', '6', '3', '5', '4'], dtype='<U1')
np.array(list(inp),dtype =int)
array([1, 6, 3, 5, 4])

Question 7

Write a function

prime_numbers(numbers)

that accepts a list of integers and returns a new list containing only the prime numbers.

Example

Input:
[4, 7, 10, 13, 18, 23, 1]

Output:
[7, 13, 23]
nums_list = [4,7,10,13,18,23,1]
nums_array = np.array(nums_list)
nums_array
array([ 4,  7, 10, 13, 18, 23,  1])
is_prime = lambda n: n>1 and all(n%i!=0 for i in range(2,n))
np.array([10])%np.array([1,2,34])
array([ 0,  0, 10])
[10]%[1,2,33]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/tmp/ipykernel_1350/4267519414.py in <cell line: 0>()
----> 1 [10]%[1,2,33]

TypeError: unsupported operand type(s) for %: 'list' and 'list'
is_prime = lambda n: n>1 and all(n%(np.arange(2,n,1))!=0)
is_prime(20)
False
def prime_list(numbers):
  dummy_list = []
  for i in range(len(numbers)):
    if is_prime(numbers[i]):
      dummy_list.append(numbers[i])
  return dummy_list
nums_array[np.vectorize(is_prime)(nums_array)]
array([ 7, 13, 23])