Improve performance of a for loop in Python (possibly with numpy or numba)
I want to improve the performance of the for loop in this function. import numpy as np import random def play_game(row, n=1000000): """Play the game! This game is a kind of random walk. Arguments: row (int[]): row index to use in the p matrix for each step in the walk. Then length of this array is the same as n. n (int): number of steps in the random walk """ p = np.array([[ 0.499, 0.499, 0.499], [ 0.099, 0.749, 0.749]]) X0 = 100 Y0 = X0 % 3 X = np.zeros(n) tempX = X0 Y = Y0 for j in range(n): tempX = X[j] = tempX + 2 * (random.random() < p.item(row.item(j), Y)) - 1 Y = tempX % 3 return np.r_