In this lecture, we will to continue to learn NumPy array
, and we will use flow control loops to manunipulate arrays.
ndarray
is an arbitrary dimension set of variables of the same type (cf. list
can be concatenate different types). In default, one entry of an array is a 64-bit float (a real number represented by 64 binary digit).
shape
, reshape
, arange
.# always run this cell block first
import numpy as np
arr = np.array(range(10))
print(arr)
arr[-1] # [] is used for array indexing, () is used as input of functions
Very clever way to repeat actions.
Syntax:
while CONDITION FOR DOING THE NEXT ITERATION OF THE LOOP:
STUFF THAT WILL BE REPEATED IN EVERY ITERATION
# generate lst which is a list of integers from 0 to 9 using while
# code here
n = 0 # counter
lst = [] # initialize the list
while n < 10:
lst.append(n) # the code to be executed if n < 10
n = n + 1 # increase the counter by 1
We want to write a function called isprime
that checks if a number is prime. Returns True
if number is prime, False
otherwise.
def isprime(n):
# insert code here
# we check all the divisor d < n whether n % d is 0
# recall n % d is the modulo operation,
# which return the remainder of the division using divisor d
# while loop version: generating an array
arr = np.empty([100], dtype = 'int')
k = 1
while k <= 100:
arr[k-1] = k
k += 1
# for loop version
These are keywords:
break
was called, it stopped the loop without doing the print statement underneath.continue
skips the rest of the current looping of the loop but continues to loop as usual afterwards//
as division(a,b)
. Make sure you are doing the negative number examples correctly.which comes from the Taylor expansion of $\arctan(x)$.
Write a code snippet to compare the answer to the built-in math.pi
.
Instead of iterating along the indices, we can use built-in routine to make our execution more efficient.
arr = np.array(range(16))
arr = arr.reshape(4,4) + 1
arr.reshape(2,2,-1) # if you put -1, it figures out what the shape should be
arr
np.reshape(arr, (2,2,-1)) # -1 means unspecified
np.sum(arr)
np.mean(arr)
np.apply_along_axis()
np.apply_along_axis(np.sum, 0, arr)
np.apply_along_axis(np.sum, 1, arr)
np.sum(arr, axis=1)