0

I was looking for help writing this code for a program that simulates a random walk of 25 steps.

The (person) can either walk East or West.

The program has to compute and output to the screen the following:

The average distance from the starting point at the end of the 25 steps. The average number of times that the random walk returned to the starting point during the 25 steps.

Also it simulates a random walk of increments: 1 step, then 2 steps, then 3 steps, then 4 steps, ..., up to 50 steps.

Note: 1 = east and 2 = west

This is what I have so far, any suggestions would be greatly appreciated.

import random
x = 0
y = 0
def randomWalk(N):
  for i in range (1, (N)):
    a = random.randint
    if a == 1:
        x = x+1
        y = y+0
        return (x, y)
        print (x, y)
    if a == 2:
        x = x+0
        y = y-1
        return (x, y)
        print (x, y)
  • 1
    and what is the problem ? To me seems that you just don't call the randint method (even with the good bounds) but just assigning it – azro Nov 16 '19 at 21:39
  • 2
    Your print statement after return never gonna be executed, you need to place the print statement before the return statement. – Marios Keri Nov 16 '19 at 21:51
  • You should reformulate better your question, because its not clear – Cristofor Nov 16 '19 at 21:55

1 Answers1

0

I have created an algorithm that you can learn from. In the code, I added comments that describe the changes I made and the areas your code was not working.

import random

def randomWalk(N):
    # It's best to initialize variables inside a function
    # Here, I assumed x is the position relative to the starting point
    # while y is the number of times the person crossed the starting point (0)
    x = 0
    y = 0
    # You would want a range from 0 to N
    # This is because you want N steps
    for i in range(N):
        # Make sure you are calling random.randint by using parentheses
        # The function takes in two arguments, which specify the bounds, inclusive
        a = random.randint(1, 2)
        if a == 1:
            # Instead of doing x = x + 1 you can do x += 1
            x += 1
        else:
            # Same thing here
            x -= 1
        # This detects whether the person is on the starting point
        # and adds 1 to y if they are
        if x == 0:
            y += 1
    # You want to return x and y at the end of the for loop
    # You were previously returning it after 1 iteration
    return x, y

# Testing randomWalk with 15 steps
print(randomWalk(15))
aiyan
  • 406
  • 4
  • 11