Prepin
Log in

Create a function that simulates 25 flips of a coin with an equal probability of heads or tails. The function should return the total count of heads obtained.

Approach / Explanation

This inquiry is about creating a function to simulate the flipping of a coin, specifically for a total of 25 flips. Each coin flip has two possible outcomes, 'heads' or 'tails', both of which have an equal chance of occurring, resulting in a 50/50 probability. The goal of the function is to output the total number of 'heads' obtained. To efficiently address this issue, the following important considerations can be taken into account: How to represent the coin? (Heads and Tails can be denoted by 0 and 1, or as the strings 'Heads' and 'Tails') How to generate randomness in binary or boolean form (true/false) necessary for simulating the coin flip. How to perform the flip 25 times? How to tally the number of occurrences of 'heads'? We can utilize Python's random library to create randomness and implement a loop to repeat the process 25 times. Additionally, we need to keep track of the results, specifically the frequency of 'heads' that we encounter during the flips.

Suggested Answer

Here’s a rephrased version of the content while retaining its original meaning: ```python import random def coin_flip_simulation(): flips = [random.choice(['Heads', 'Tails']) for _ in range(25)] return flips.count('Heads') ``` In this Python script, I utilized list comprehension to simulate flipping a coin 25 times. For each flip, I employed `random.choice` to randomly choose between 'Heads' or 'Tails'. The results are stored in a list named `flips`. I then count the occurrences of 'Heads' in `flips` and return that total.

Alternative Answer

In this Python snippet, I utilized the NumPy library. The function `np.random.choice` randomly selects either 'Heads' or 'Tails', repeating this process 25 times to generate an array containing 25 elements. The function `np.count_nonzero` is used to tally the number of non-zero entries in the array that meet a specific condition. In this case, it counts how many times the element is 'Heads'. The function then returns this count.

Question Details

Difficulty & Category

Medium
coding

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.