Hi all, my Professor has asked us to solve this problem, which is a Midterm Practice problem for our up and coming Midterm exam, which is on Monday. I am wondering if I'm doing this the correct way or not.

Here is this question the problem asks:

Problem 19 Random Steps
Write a function named randomSteps() that simulates a person taking a specified number of steps of
varying length. The length of the steps varies at random within a specified range. (Use the function in
the random module random.randint(a, b), which returns a random integer N such that a <= N <= b.)
Input:
Parameter 1: minStep, an integer >= 0 that is the minimum length of a single step
Parameter 2: maxStep, an integer > 0 that is the maximum length of a single step
Parameter 3: steps, an integer > 0 that is the total number of steps to be taken
Return:
An integer that is the distance walked
Assume that the parameters are in the specified range. Because the steps are of random length,
successive calls to randomSteps() with the same parameters may produce different output. An example
of a call of randomSteps() and its output would be:
>>> print(randomSteps(2, 5, 100))
>>> 355


Following the instructions, I've come up with this for my code:

import random


def randomSteps(minStep, maxStep, distance):
length = 0
while length < distance:
length = random.randint(minStep, maxStep)
length += minStep
distance -= length
return length


print(randomSteps(2, 5, 100))


I normally get an output (with these variables) of 5, 6, or sometimes 7. Can anyone tell me if this is correct, or what should I change to make it correct, or at least guide me :). Thanks so much!

Your third parameter breaches the contract. It said that the third parameter must be the number of steps to be taken. It means that randint() must be called exactly this number of times.

Okay so how exactly would I alter that? I'm not very familiar with the randint() and using variables with it.

here is what comes to my mind, but you need to add some codes to take the inputs and check their correctness:

import random

def distance(minlen, maxlen, steps):
    total_distance = 0
    step_count = 0
    while step_count < steps:
        step_length = random.randint(minlen, maxlen)
        total_distance += step_length
        step_count += 1
    return total_distance
  
print distance(2, 6, 100)

Edited 4 Years Ago by M.S.: n/a

This article has been dead for over six months. Start a new discussion instead.