1

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)

1 Answer 1

1

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))
Sign up to request clarification or add additional context in comments.

1 Comment

There is no need for a list comprehension here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.