Question

1 [Run Lengths] Write a function (in Python and numpy) with the following specification def run_lenths(n,...

1 [Run Lengths] Write a function (in Python and numpy) with the following specification def run_lenths(n, p): """Return a list of the run lengths in n tosses of a coin whose heads probability is p. Arguments: n--Number of tosses (a positive int), p--The probability of observing heads for any given toss (float between 0 and 1). """ For example, if the simulated sequence of coin tosses is HTTHHTHHHTTHHTTTTH, then the list of run lengths the function returns will be [1, 2, 2, 1, 3, 2, 2, 4, 1]. Hint: Your function should not explicitly return or print the sequence of coin tosses itself. But you will have to generate this sequence of tosses internally and derive the sequence of run lengths from it. Printing the sequence of coin tosses (for small values of n) during testing and debugging can help you verify if your function works as expected. For example, it is easy to forget to include the last run. In the next two problems, we will be interested in the maximum 1 run length (4 in the example above) and the number of runs (9 in the example above). These are given by max(run_lengths(n, p)) and len(run_lengths(n, p)), respectively.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

import random

def run_lenths(n, p):

seq = []

# generating n T/H with p probability

for i in range(n):

one = random.randint(1, 100)

if one/100 <= p:

seq.append('H')

else:

seq.append('T')

result = [] # is to hold the result

count = 1

for i in range(1, len(seq)):

if seq[i] == seq[i-1]:

count += 1

else:

result.append(count)

count = 1

result.append(count)

return result

print(run_lenths(18, 0.6))

# SAMPLE OUTPUT: [1, 2, 1, 2, 3, 5, 1, 1, 2]

# Hit the thumbs up if you are fine with the answer. Happy Learning!

Add a comment
Know the answer?
Add Answer to:
1 [Run Lengths] Write a function (in Python and numpy) with the following specification def run_lenths(n,...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT