Python program to design a biased coin flip function

An example of random.choice() in Python: Here, we are going to learn how to design a function that can be used as biased coin flip and the function will return a random value of biased coin flip? By Anuj Singh Last updated : January 12, 2024

Problem statement

Write a Python program to design a biased coin flip function.

Solution overview

Here, we are going to build a biasedcoin() function using Python. The program is so simple as an introductory program and similar to the function coin() for defining a biased coin flip. The function is going to use an inbuilt library naming random. This random python library helps us to choose a random value of the variable within the range or take some random value from a given set.

Designing a biased coin flip function

To design a biased coin flip function, use the random.choice() method and pass the list value ['H', 'T', 'H'] as the parameter, when the function is called, it will return a random value from the given list.

Consider the below statement:

random.choice(['H','T','H'])

The above function will choose a random value with a probability of:

COIN FLIP =  PROBABILITY OF OCCURRENCE
-    HEAD = 0.67
-    TAIL = 0.34

Each member of the set have equal probability to get fired when random.choice() function is called and if a member is present multiple times in the set, its probability increases as well.

Python program to design a biased coin flip function

import random

# function to return the randon value
# on biased biased coin FLIP
def biasedcoin():
    return random.choice(["H", "T", "H"])

# main code i.e. function calling
print("COIN FLIP : ", biasedcoin())
print("COIN FLIP : ", biasedcoin())
print("COIN FLIP : ", biasedcoin())
print("COIN FLIP : ", biasedcoin())
print("COIN FLIP : ", biasedcoin())

Output

The output of the above program is:

RUN 1:
COIN FLIP :  H
COIN FLIP :  T
COIN FLIP :  H
COIN FLIP :  H
COIN FLIP :  H

RUN 2:
COIN FLIP :  T
COIN FLIP :  H
COIN FLIP :  H
COIN FLIP :  T
COIN FLIP :  H

To understand the above program, you should have the basic knowledge of the following Python topics:

Python Basic Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.