Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Using Python-- Implement function heads() that takes no input and simulates a se

ID: 3771873 • Letter: U

Question

Using Python-- Implement function heads() that takes no input and simulates a sequence of coin flips. The simulation should continue as long as 'HEAD' is flipped. When the outcome of a flip is 'TAIL', the function should return the number of 'HEAD' flips made up to that point. For example, if the simulation results in outcomes 'HEAD', 'HEAD', 'HEAD', 'TAIL', the function should return 3. NOTE: Recall that random.choice(['HEAD', 'TAIL']) returns 'HEAD' or 'TAIL' with equal probability.

>>> heads() 0 # TAIL is the outcome of the first coin flip

>>> heads() 2 # The coin flips were HEAD, HEAD, TAIL

>>> heads() 1 # The coin flips were HEAD, TAIL

Explanation / Answer

Python Program Code:

import random;

def heads():
   outcome = random.choice(['HEAD','TAIL']);
   head_cnt = 0;
   while outcome != "TAIL":
       print(" " + outcome);
       outcome = random.choice(['HEAD','TAIL']);
       head_cnt = head_cnt + 1;
  
   return head_cnt;
  
def main():
   head_cnt = heads();
   print(" Total Number Of Heads: " + str(head_cnt));
  
  
if __name__ == "__main__":
main()

-----------------------------------------------------------------------------------------------------------------------------------------------------------

Sample Run:

C:Python33>python qa_14_12.py
HEAD
HEAD


Total Number Of Heads: 2

C:Python33>python qa_14_12.py
HEAD
HEAD


Total Number Of Heads: 2

C:Python33>python qa_14_12.py


Total Number Of Heads: 0

C:Python33>python qa_14_12.py


Total Number Of Heads: 0

C:Python33>python qa_14_12.py
HEAD


Total Number Of Heads: 1

C:Python33>python qa_14_12.py


Total Number Of Heads: 0

C:Python33>python qa_14_12.py
HEAD
HEAD
HEAD
HEAD


Total Number Of Heads: 4

C:Python33>

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote