Question

Python: Write a bit of code that will simulate 100 random, independent coin flips. Write code...

Python: Write a bit of code that will simulate 100 random, independent coin flips. Write code that will count the number of changes (Heads to Tails or Tails to Heads. For example, the sequence H, H, T, T, H, H, T has three changes.) in a sequence of coin flips. Hint: You can change the sequence to True/False by using: mysequence == 'Heads'. Once you have changed Heads/Tails to True/False, try figuring out a way to use the np.diff method followed by the np.sum method to count the number of changes.

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

SOURCE CODE IN PYTHON:

import numpy as np

#function to simulate a toss and return the value

def toss():

res=np.random.randint(2)

if res==0:

return 'Heads'

else:

return 'Tails'

#to store the result of tosses

tosses=[]

#simulating 100 tosses and storing True for Heads and False for tails

for i in range(100):

tosses.append(toss()=='Heads')

#np.diff() returns a list of boolean values that indicate

#if there were different values in adjacent cells

#np.sum() returns the number of True values, hence returning

#number of changes

changes=np.sum(np.diff(tosses))

#output

print('No. of changes:', changes)

OUTPUT:

Add a comment
Know the answer?
Add Answer to:
Python: Write a bit of code that will simulate 100 random, independent coin flips. Write code...
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