import random
random.random()
def coin_toss(p = 0.5):
if random.random() < p:
return 'H'
else:
return 'T'
for _ in range(10):
print(coin_toss(0.9))
random.randint(0,10)
l = [0.5,4,27,'apple',53.8]
random.choice(l)
random.seed(20)
random.random()
np.roll
¶import numpy as np
A = np.reshape(np.arange(0,25),(5,5))
print(A)
np.roll(A,(-1,0),(0,1))
A = np.zeros((6,6))
A[1:5,1:5] = 1
print(A)
B = np.zeros((6,6))
for i in range(-1,2):
for j in range(-1,2):
B += np.roll(A,(i,j),(0,1))
B -= A
B[1:5,1:5]
Exercise: Write a function that takes an array as input and returns an array where each entry is the neighbor sum from the input array, calculated using np.roll
.
def neighbor_sum(arr):
i,j = np.shape(arr)
border_arr = np.zeros((i+2,j+2),dtype=int)
border_arr[1:i+1,1:j+1] = arr
sum_arr = np.zeros((i+2,j+2),dtype=int)
for r in range(-1,2):
for c in range(-1,2):
sum_arr += np.roll(border_arr,(r,c),(0,1))
return sum_arr[1:i+1,1:j+1] - arr
A = np.reshape(np.arange(0,9),(3,3))
print(A)
np.roll(A,(-1,1),(0,1))
np.roll(A,(-1,0),(0,1))
np.roll(A,(-1,-1),(0,1))
B = neighbor_sum(np.ones((5,5)))
print(B)
fives = 1-np.ceil(np.absolute((B-5)/10))
neighbor_sum(fives)
bool_arr = B == 5
bool_arr
np.array(bool_arr,dtype = int)
Array of 0s and 1s with the 1s representing living cells and the 0s non-living cells.
Rules for how life evolves
def Conway(arr):
living_neighbors = neighbor_sum(arr)
arr = (arr + np.array((np.array(living_neighbors < 2,dtype=int) + A) == 2,dtype=int)
+ np.array((np.array(living_neighbors > 3,dtype=int) + A) == 2,dtype=int)
+ np.array((np.array(living_neighbors == 3,dtype=int) - A) == 1,dtype=int))%2
return arr
A = np.random.randint(0,2,(20,20))
A
A = Conway(A)
A