Skip to content
DeepForgeby svx
All problems
EasyProbabilitypr-265

Random Walk Variance After n Steps

Problem

For a random walk with steps +1 with probability p and -1 otherwise, the position after n steps has variance 4 * p * (1 - p) * n. Return that variance, or 0.0 for n < 0 or p outside [0, 1].

Hint

Each step has variance 4 * p * (1 - p) and the steps are independent.

Test cases

case 1
in: [10,0.5]
expected: 10
case 2
in: [5,0.3]
expected: 4.2
case 3
in: [0,0.5]
expected: 0
case 4
in: [7,1]
expected: 0
case 5
in: [3,0.25]
expected: 2.25
Starter codePython
def random_walk_variance(n, p):
    # Your code here
    pass

5 test cases · run your code against them in the editor