Im trying to convert this code into one-liner function using lambda and numpy, the function should return numpy array, but i dont know how to save the step value for each iteration
import random
def generate_array(n: int):
step = 1
arr = []
for i in range(n):
step = step 1 if random.choice([True, False]) else step - 1
arr .append(step)
return arr
generate_array(10)
CodePudding user response:
You can first create the difference array using np.random.choice
, and then sum each item up cumulatively using np.cumsum()
:
np.cumsum(np.random.choice([1, -1], size=10))