Flipping a Coin in Python
There are many ways to create a coin flipper, but there is an elegant way, using the singleton design pattern. In brief, singletons mean that you instantiate a single object from a class at one time, in this case, its heads or tails.
from enum import Enum, auto
Enum: is our data type.
Auto: assign value starting from 1.
Random: is a pseudo-random number generator.
Create a coin:
heads = auto()
tails = auto()list(Coin) #=> [<Coin.heads: 1>, <Coin.tails: 2>]
The class coin has two variables (heads and tails).
Heads have the value 1, while tails have the value 2.
Creating the Flip Function:
def flip() -> Coin:
return random.choice(list(Coin))flip() #=> <Coin.heads: 1>
The function flip utilizes the choice method from the random library.
Create a list of flips.
heads_list = [flip() for _ in range(1000)]
heads_list.count(Coin.heads) #=> 514
heads_list.count(Coin.tails) #=> 486
Using a comprehension list of 1000 flips.
We get the following count; the values are almost 50–50 because the choice function produces a uniform distribution (where each value is equally likely to be picked).
Use enum to create a singleton when you have a list of defined constants, and you want to draw a single object.