Question: Modify the below program (Python, Object-oriented programming) Define a class Walker. The class constructor (__init__) should take in an integer to specify initial position (so

Modify the below program (Python, Object-oriented programming)

Define a class Walker. The class constructor (__init__) should take in an integer to specify initial position (so the random walk could begin from anywhere instead of from 0). The class should maintain a field specifying its position, which one could call with the .get_position() method. Write a method .walk(nsteps,filename) to simulate a random walk of length nsteps, updating its position at the end of the walk. The second argument into the method should be optional, however, if specified a filename, the object should write the sequence of positions generated during the walk into a file (.csv, 1 column, nsteps number of entries). Finally, implement a method called .check_collision(another_walker) that takes as input a Walker object, gets its position and returns True/False on whether or not it shares the same position as the walker object that calls it.

import random import matplotlib.pyplot as plt

steps=[] def func(nsteps,nsim): for j in range(nsim): #loop for simulations distance=0 for i in range(nsteps): #loop for steps coin = random.randint(1, 2) if coin==1: distance=distance+1 else: distance=distance-1 steps.append(distance) #appending average steps to list return steps

nsteps=100 nsim=10 steps=func(nsteps,nsim) #calling function

#for plotting N = len(steps) x = range(N) width = 1/1.5 colors=['b','r','g','tan','lime','pink','orange','black','brown','silver'] fig=plt.bar(x, steps, width, align='center',color= colors) plt.savefig('walk.png') plt.show()

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!