I wrote a doctest in "I tried to simulate the probability of a bingo game with Python"

Original story Original story: [I tried to simulate the probability of a bingo game with Python] (http://qiita.com/elzup/items/d532ffa1d326fbf75d01) Original story: [I tried to fix "I tried to simulate the probability of a bingo game with Python"] (http://qiita.com/t2y/items/8584b77b3fe02dd2ce63)

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

One of the features of Python is doctest. If you combine the document of how to use the function with a simple test, it may be two birds with one stone.

If you modify the logic of the original code so as not to mess with it, the doctest of the modified code is not good, but if you try to develop while writing the doctest, the perspective of the position to use will expand and it will be easy to use naturally. You can implement functions and modules.

While writing doctest, if you develop it interactively, it will be easy to debug, it will be an easy-to-use API, and I wanted to say that it can be used as a document as it is, but I could not write appropriate sample code, so revenge.

I tried to make it easier to understand the purpose of doctest.

As an aside, I've been wondering if I could write the card number generation process more clearly from yesterday, and I was a little happy when I used * reduce *.

    def _generate(self):
        def sampling(k=5):
            for i in range(k):
                yield sample(range(15 * i + 1, 15 * (i + 1) + 1), k)

        return reduce(add, sampling())

I would be happy if I could convey this kind of atmosphere.

# -*- coding: utf-8 -*-
from functools import reduce
from operator import add
from random import sample


class Card:
    """ 75-ball Bingo Card

    The middle square is designated a "FREE" space.
    The columns are labeled as follows.
    "B": (numbers 1–15)
    "I": (numbers 16–30)
    "N": (numbers 31–45)
    "G": (numbers 46–60)
    "O": (numbers 61–75)

    http://en.wikipedia.org/wiki/Bingo_card

    >>> data = [  # for testing use
    ... 1, 2, 3, 4, 5,
    ... 6, 7, 8, 9, 10,
    ... 11, 12, 13, 14, 15,
    ... 16, 17, 18, 19, 20,
    ... 21, 22, 23, 24, 25,
    ... ]
    >>> card = Card(data)
    >>> len(card.numbers)
    25
    >>> card.numbers[12]
    True
    >>> card.is_bingo
    False
    >>> print(card)
      1  2  3  4  5
      6  7  8  9 10
     11 12  o 14 15
     16 17 18 19 20
     21 22 23 24 25

    Show 'o' when giving number is found

    >>> card.set_number(14)
    >>> print(card)
      1  2  3  4  5
      6  7  8  9 10
     11 12  o  o 15
     16 17 18 19 20
     21 22 23 24 25

    Check bingo giving number to the card.

    >>> card.set_number(35)  # have no effect if number not in card.numbers
    >>> card.set_number(1)
    >>> card.set_number(7)
    >>> card.set_number(19)
    >>> card.is_bingo
    False
    >>> card.set_number(25)
    >>> card.is_bingo
    True
    >>> print(card)
      o  2  3  4  5
      6  o  8  9 10
     11 12  o  o 15
     16 17 18  o 20
     21 22 23 24  o
    """

    def __init__(self, numbers=None):
        self.numbers = self._generate() if numbers is None else numbers
        self.numbers[12] = True
        self.is_bingo = False

    def __repr__(self):
        ascii_card = ''
        for i in range(int(len(self.numbers) / 5)):
            for num in self.numbers[5 * i:5 * (i + 1)]:
                if num is True:
                    num = 'o'
                elif num is False:
                    num = 'x'
                ascii_card += '{0:>3s}'.format(str(num))
            ascii_card += '\n'
        return ascii_card[:-1]

    def _generate(self):
        def sampling(k=5):
            for i in range(k):
                yield sample(range(15 * i + 1, 15 * (i + 1) + 1), k)

        return reduce(add, sampling())

    def set_number(self, number):
        if number not in self.numbers:
            return
        self.numbers[self.numbers.index(number)] = True
        if not self.is_bingo:
            self.check_bingo()

    def check_bingo(self):
        def check(start, stop, step=1):
            return all(map(lambda x: x is True, self.numbers[start:stop:step]))

        if self.numbers.count(True) < 5:
            return

        for i in range(5):
            if check(i * 5, (i + 1) * 5):  # horizontal
                self.is_bingo = True
                return

        for i in range(5):
            if check(i, i + 21, 5):  # vertical
                self.is_bingo = True
                return

        if check(0, 25, 6) or check(4, 21, 4):  # skew
            self.is_bingo = True
            return

Run doctest like this.

$ python -m doctest Bingo_kai2.py  #If no error is displayed, the test is correct
$ python -m doctest Bingo_kai2.py -v  #Redundant mode

Recommended Posts

I wrote a doctest in "I tried to simulate the probability of a bingo game with Python"
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 tried to implement a card game of playing cards in Python
I tried to find the entropy of the image with python
I tried to simulate how the infection spreads with Python
I tried to implement blackjack of card game in Python
[Python & SQLite] I tried to analyze the expected value of a race with horses in the 1x win range ①
I tried to create a list of prime numbers with python
I wrote the code to write the code of Brainf * ck in python
I tried to implement a misunderstood prisoner's dilemma game in Python
I tried to improve the efficiency of daily work with Python
I tried to create a Python script to get the value of a cell in Microsoft Excel
I tried playing a typing game in Python
I want to make a game with Python
I tried to get the authentication code of Qiita API with Python.
I tried to streamline the standard role of new employees with Python
I made a program to check the size of a file in Python
I tried to display the altitude value of DTM in a graph
A story that didn't work when I tried to log in with the Python requests module
I tried to make a simple mail sending application with tkinter of Python
I tried to touch the CSV file with Python
I tried to draw a route map with Python
I tried to solve the soma cube with python
I tried to implement a pseudo pachislot in Python
I tried to open the latest data of the Excel file managed by date in the folder with Python
I tried to easily visualize the tweets of JAWS DAYS 2017 with Python + ELK
I want to work with a robot in python.
I tried to automatically generate a password with Python3
How to get a list of files in the same directory with python
I tried to create a model with the sample of Amazon SageMaker Autopilot
I tried to automatically send the literature of the new coronavirus to LINE with Python
I tried to summarize the string operations of Python
I wanted to know the number of lines in multiple files, so I tried to get it with a command
Introduction to AI creation with Python! Part 2 I tried to predict the house price in Boston with a neural network
I tried to make something like a chatbot with the Seq2Seq model of TensorFlow
How to identify the element with the smallest number of characters in a Python list?
I tried to put out the frequent word ranking of LINE talk with Python
I tried to automate the article update of Livedoor blog with Python and selenium.
[Python] I tried to automatically create a daily report of YWT with Outlook mail
I tried to compare the processing speed with dplyr of R and pandas of Python
The 15th offline real-time I tried to solve the problem of how to write with python
I made a simple typing game with tkinter in Python
I tried the accuracy of three Stirling's approximations in python
I tried to find the average of the sequence with TensorFlow
I tried to implement a one-dimensional cellular automaton in Python
I wrote a program quickly to study DI with Python ①
I wrote the basic grammar of Python with Jupyter Lab
I tried "How to get a method decorated in Python"
[Python] I tried to visualize the follow relationship of Twitter
I tried to implement the mail sending function in Python
[Python] The first step to making a game with Pyxel
I tried to divide the file into folders with Python
I wrote the queue in Python
I wrote the stack in Python
I made a class to get the analysis result by MeCab in ndarray with python
I tried to get the number of days of the month holidays (Saturdays, Sundays, and holidays) with python
I tried to predict the sales of game software with VARISTA by referring to the article of Codexa
[5th] I tried to make a certain authenticator-like tool with python
I tried scraping the ranking of Qiita Advent Calendar with Python
I tried to describe the traffic in real time with WebSocket