Home > Software engineering >  Python coin flip with functions
Python coin flip with functions

Time:03-23

I need to create a python program that will use various functions to simulate flipping a coin 100 times and finding the largest streak of "H"'s out of 10,000 tries. I am stuck on how to finish the def main() function, specifically the counter. I also don't know if my program is calculating the streaks correctly.

def flipCoin() - returns 'H' or 'T' with the same probability as a coin.

def simulate(numFlips) - simulates flipping a coin numFlips(100) times. This function returns a list of length numFlips containing H's and T's.

def countStreak(flips_list) - iterates through the flips list passed to it and counts streaks of 'H's and returns the largest streak it finds. Keep track of the current number of heads and the current largest streak of heads in two separate variables. As you iterate through the list, keep track of the current number of heads you've seen in a row. If you see a tail, check if the current streak of heads is larger than your current longest streak. If so, save the current streak. Then reset your heads counter.

In the main function, write a testing loop that simulates the process 10000 times. Keep track of the current largest streak of heads and display this result after the test loop completes.

# import statements                                                             
import random

# function defintions                                                           
def flip():
    coin = random.randint(0, 1)
    if coin == 0:
        return "H"
    else:
        return "T"

def simulate(num_flips):
# simulates numFlips coin flips                                             
# returns a list of the flips
    numFlips = []
    for i in range(100):
        numFlips.append(flip())
    return numFlips

def countStreak(flips_list):
# iterates through the 'flips' list                                         
# returns number of 'H's
    count = 0
    maxCount = 0
    flips_list = simulate()
    for i in flips_list:
        if i == "H":
            count  = 1
            if count > maxCount:
                maxCount = count
        else:
            count = 0
    return maxCount

def main():
    for j in range(10000):
        trial = simulate(100)
        coinFlip = countStreak(1)
        # need something here to track count of streaks for "H"
    print("The longest streak of heads was "   str(coinFlip)  ".")


if __name__ == "__main__":
    main()

CodePudding user response:

So there was a flaw in your code, you were running simulate() function 10000 times. But actually, you had to run it once, but return a list of 10000 items. Also, you need not check the streak every time so the check_streak() need to be out of the loop and we need to pass the result obtained from simulate(10000) into it. Correct Code:

# import statements                                                             
import random

# function defintions                                                           
def flip():
    coin = random.randint(0, 1) # better option would be to use random.choice()
    if coin == 0:
        return "H"
    else:
        return "T"

def simulate(num):
# simulates numFlips coin flips                                             
# returns a list of the flips
    numFlips = []
    for i in range(num): # this needs to run num times
        numFlips.append(flip())
    return numFlips

def countStreak(flips_list):
# iterates through the 'flips' list                                         
# returns number of 'H's
    count = 0
    maxCount = 0
    for i in flips_list:
        if i == "H":
            count  = 1
            if count > maxCount:
                maxCount = count
        else:
            count = 0
    return maxCount

def main():
    trial = []
    for j in range(10000):
        temp2 = simulate(100) # SImulate 10000 coin flips
        coinFlip = countStreak(temp2) # Check streak of variable trial
        trial.append(coinFlip)
        # need something here to track count of streaks for "H"
    # print(trial)
    print("The longest streak of heads was "   str(max(trial))  ".")

if __name__ == "__main__":
    main()

This Part is Optional, For optimisation

Though the logic isn't wrong, you need not make the list 1st and then check streak, you can simply check it together, it will take less time and space.
Also, your logic is correct, but this one would be better:

import random

# function defintions                                                           
def flip():
    return random.choice(['H', 'T']) # using random.choice()

def simulate(num_flips):
    streak = 0
    temp = 0    
    for i in range(num_flips):
        if flip() == 'H':
            temp =1 # adding one to temporary streak if it is a heads
        else: # this block executes if streak is broken
            if temp > streak:
                streak = temp
            temp = 0
    return streak

def main():
    trial = []
    for i in range(10000):
        trial.append(simulate(100))
    print("The longest streak of heads was "   str(max(trial))  ".")


if __name__ == "__main__":
    main()
  • Related