I tried a stochastic simulation of a bingo game with Python

Suddenly code

Bingo.py


# -*- coding: utf-8 -*-

u"""Script that simulates the probability of BINGO
input:
    times =Number of times to turn the lottery machine, card_num =Number of cards
outpu:
Probability of getting even one

"""
import sys
from random import sample

#hole
HIT = True
NOHIT = False


def generate_card():
    u"""Generate card
5x5 center(3 rows 3 columns)Card with a hole in
    B(1st row) 1 - 15
    I(2nd row) 16 - 30
    N(3rd row) 31 - 45
    G(4th row) 46 - 60
    O(5th row) 61 - 75
    :returns: array card, length=25

    """
    cards = []
    for i in range(5):
        cards.extend(sample(range(15 * i + 1, 15 * (i + 1)), 5))
    cards[12] = HIT
    return cards


def check_bingo(card):
    u"""Whether you are BINGO
Judgment only
    param: array
    :returns: boolean
    """
    if card.count(HIT) < 5:
        return False
    for i in range(5):
        if NOHIT not in card[i * 5: (i + 1) * 5]:
            return True
    for i in range(5):
        if NOHIT not in card[i: i + 21: 5]:
            return True
    if NOHIT not in card[0: 24: 6]:
        return True
    if NOHIT not in card[4: 21: 4]:
        return True
    return False


def print_card(card):
    for i, v in enumerate(card):
        if v == HIT:
            v = "o"
        elif v == NOHIT:
            v = "x"
        sys.stdout.write("%3s" % str(v))
        if (i % 5 == 4):
            print()
    print()


try:
    times = int(sys.argv[1])
except IndexError:
    times = 5
try:
    card_num = int(sys.argv[2])
except IndexError:
    card_num = 10000

hit_count = 0
for i in range(card_num):
    card = generate_card()
    lots = sample(range(1, 76), times)
    card_hole = [(HIT if (x == HIT or x in lots) else NOHIT) for x in card]
#    print_card(card)
#    print_card(card_hole)
    if check_bingo(card_hole):
        hit_count += 1

print(str(times) + u"Probability of BINGO even one at the first time:")
p = hit_count / card_num
print("%s (%.1f %%)" % (str(p), p * 100))

Gist: https://gist.github.com/0c11f757334ba9ef7b1f

input: Number of times to turn the lottery machine Number of cards (number of simulations) output: Probability of even one BINGO

The explanation of each function should be mostly understood in the comments

  1. Card generation
  2. Batch generation of drawn lottery
  3. Make a hole in the card
  4. BINGO judgment Loop

The part where you can write like Python I think that the part that judges whether the card (BINGO card) is hit or not can be written like Python (I just wanted to make a process here)

#Judgment in the 4th column
NOHIT not in card[3:3 + 21:5]
#Judgment diagonally from top left to bottom right
NOHIT not in card[0:24:6]

Python arrays can be retrieved with array [start: end: step], so judgments can be written smartly.

Execution output example

>> python3 bingo.py 5 10000
Probability of even one BINGO in the 5th time:
0.0003 (0.0 %)

It doesn't matter, but what I learned in Flake 8 this time as a Python coding standard You have to open two lines between functions Do not put spaces on the ** right side ** of the array colon (same as the comma in the argument)

I still don't know how to write a doc block, so I'll study

Recommended Posts

I tried a stochastic simulation of a bingo game with Python
I tried to fix "I tried stochastic simulation of bingo game with Python"
I wrote a doctest in "I tried to simulate the probability of a bingo game with Python"
I tried a functional language with Python
I made a roguelike game with Python
I tried to create a list of prime numbers with python
I tried hundreds of millions of SQLite with python
I tried playing a typing game in Python
I want to make a game with Python
I made a bin picking game with Python
I tried to implement a card game of playing cards in Python
I tried fp-growth with python
I tried scraping with Python
I tried gRPC with Python
I tried scraping with python
I tried to draw a route map with Python
[OpenCV / Python] I tried image analysis of cells with OpenCV
I tried to automatically generate a password with Python3
I tried using Python (3) instead of a scientific calculator
I tried "morphology conversion" of images with Python + OpenCV
I tried to make a simple mail sending application with tkinter of Python
I tried to find the entropy of the image with python
I tried "gamma correction" of the image with Python + OpenCV
I made a simple typing game with tkinter in Python
I tried web scraping with python.
I tried running Movidius NCS with python of Raspberry Pi3
Life game with Python! (Conway's Game of Life)
[Python] I tried to automatically create a daily report of YWT with Outlook mail
I made a puzzle game (like) with Tkinter in Python
I tried running prolog with python 3.8.2.
I made a daemon with Python
I tried SMTP communication with Python
I tried to implement blackjack of card game in Python
[5th] I tried to make a certain authenticator-like tool with python
I tried scraping the ranking of Qiita Advent Calendar with Python
Save the result of the life game as a gif with python
[2nd] I tried to make a certain authenticator-like tool with python
I tried to make a regular expression of "amount" using Python
[System trade] I tried playing with Stochastic Oscillator by decomposing with python ♬
I tried to make a regular expression of "time" using Python
[3rd] I tried to make a certain authenticator-like tool with python
[Python] A memo that I tried to get started with asyncio
I made a lot of files for RDP connection with Python
I tried to implement a misunderstood prisoner's dilemma game in Python
I tried to make a periodical process with Selenium and Python
I tried to make a 2channel post notification application with Python
I tried to make a todo application using bottle with python
I made a poker game server chat-holdem using websocket with python
I tried to improve the efficiency of daily work with Python
I tried to automatically collect images of Kanna Hashimoto with Python! !!
I tried to make a mechanism of exclusive control with Go
Let's make a shiritori game with Python
I tried scraping Yahoo News with Python
I made a character counter with Python
I tried playing a ○ ✕ game using TensorFlow
I drew a heatmap with seaborn [Python]
I tried sending an email with python.
I tried recursion with Python ② (Fibonacci sequence)
I made a Hex map with Python
I made a life game with Numpy
I tried 3D detection of a car