import numpy as np
checkerboard(5)
arr.shape
, np.shape(arr)
2.def entry_sum(arr):
summation = 0
r,c = arr.shape
for i,j in [(i,j) for i in range(r) for j in range(c)]:
summation += arr[i,j]
return summation
def entry_sum1(arr):
summation = 0
for row in arr:
for entry in row:
summation += entry
return summation
arr = np.ones((5,5))
entry_sum(arr)
checkerboard = np.zeros(25,dtype=int)
checkerboard[1::2] = 1
checkerboard = np.reshape(checkerboard,(5,5))
print(checkerboard)
checkerboard = np.zeros((5,5),dtype=int)
checkerboard[0::2,1::2] = 1
checkerboard[1::2,0::2] = 1
print(checkerboard)
arr = np.ones((5,5),dtype=int)
print(arr)
arr[:2,:2] = 0
print(arr)
arr[2::2,2::2] = 3
print(arr)
arr[[0,2,3],[1,1,4]] = 5
print(arr)
arr[1:4,1:4] = np.array([[1,2,3],[4,5,6],[7,8,9]])
print(arr)
arr1 = np.zeros((5,5),dtype=int)
arr1[1:4,1:4] = np.array([[1,2,3],[4,5,6],[7,8,9]])
print(arr1)
Exercise: Write a function that will create an $ n \times n $ array of zeros with a $3\times3$ block of ones in the middle.
def middle_ones(n,k):
arr = np.zeros((n,n),dtype=int)
arr[(n-k)//2:(n+k)//2,(n-k)//2:(n+k)//2] = 1
return arr
middle_ones(8,3)
Exercise: Write a function that returns the sum of the entries surrounding the $ (i,j) $-entry of a given array.
np.sum(arr1)
np.sum(arr1[[1,3,4],[2,2,3]])
def neighbor_sum(i,j,arr):
return summation
Exercise: Write a function that replaces every entry of a given array with the sum of its neighbors modulo 3.
import matplotlib.pyplot as plt
plt.imshow(np.random.random((10,10)),cmap='gray')
plt.show()
%matplotlib notebook
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from matplotlib import colors
x = np.zeros((200,200), dtype = int)
fig = plt.figure(figsize = (6,6))
ax = plt.subplot(111)
plt.title("Animation test")
cmap = colors.ListedColormap(['palegreen', 'green', 'orange', 'black'])
im = ax.imshow(x, cmap = cmap, vmin = -1, vmax = 2)
def animate(i):
global x
x=update(x)
im.set_data(x)
return im
anim = FuncAnimation(fig=fig, func=animate, interval=500, blit=True, repeat=False)
plt.show()