[PYTHON] Make a math drill print

Introduction

I made a calculation drill generation program to make self-study prints for the lower grades of elementary school. Randomly create a mathematical formula with python and convert it to pdf on A4 paper size. If you print the created file at home or at a convenience store and your child learns by himself, the purpose will be achieved.

environment

ReportLab installation

To print the generated calculation formula, use ReportLab, a library for converting to pdf.

$ sudo pip3 install ReportLab

Detailed documentation on ReportLab is below. https://www.reportlab.com/docs/reportlab-userguide.pdf

Output image

This time, 2-digit addition, subtraction, and multiplication are output to the print. image002.png

How to use pdf output functions drawString and line

This print creation is mainly realized by using two functions, drawString () and line (). Before entering the program itself, I will summarize only the basic usage.


from reportlab.pdfgen import canvas
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.lib.pagesizes import A4

#Create Canvas. Specify file name and size
c = canvas.Canvas("calc_train.pdf",pagesize=A4)
#Set output coordinates
x=0
y=0
# "hoge"Coordinates the character string(0,0)Export to
c.drawString(x,y,"hoge")
#Draw a straight line
c.line(x,y,x+10,y)
#Generate pdf1 page
c.showPage()
#Save file
c.save()

The origin of ReportLab coordinates is the "bottom left" of the page.

Calculation drill automatic generation program

The following is the calculation drill automatic generation program using ReportLab, which is the purpose of this time.

import os, sys
import random

from reportlab.pdfgen import canvas
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.lib.pagesizes import A4

#Basic coordinates of 5x5 formula
x_list = [20, 130,  240, 350, 460]
y_list = [730, 580, 430, 280, 130]
#It is also possible to specify the font
fontname = "Helvetica"
#To output Japanese, set as follows.
#Please refer to your environment for the path.
#pdfmetrics.registerFont(TTFont(fontname,"/mnt/c/Windows/Fonts/msgothic.ttc"))

#A function that outputs one calculation formula to the specified coordinates
#The expected calculation is that each element is 2 digits or less.
def Set_calc(c,x,y,ope,d1,d2):
    # c: canvas
    # x, y :Coordinate
    # ope :Mathematical symbol strings
    offset = 30
    _d1 = str(d1)
    _d2 = str(d2)
    #Character width adjustment
    if(d1<10):
        _d1 = " " + _d1
    if(d2<10):
        _d2 = " " + _d2        
    c.drawString(x+offset, y,        _d1)
    c.drawString(x,        y-offset, ope)
    c.drawString(x+offset, y-offset, _d2)
    c.line(x,y-offset-5,x+offset*2.5,y-offset-5)

#A function that generates a calculation formula for one page
def Make_page(c,ope,d1_max,d2_max):
    # c: canvas
    # ope :Mathematical symbol strings
    # d1_max, d2_max :Maximum value setting for the value to be calculated
    c.setFont(fontname,20)
    #String output of header part
    c.drawString(5,800, " Name:  Day: /   ")
    c.setFont(fontname,30)

    # Set Value
    for row in y_list:
      for col in x_list:
        #Randomly generate elements within the set maximum value
        d1 = random.randint(1, d1_max)
        d2 = random.randint(1, d2_max)
        #In the case of addition
        if(ope=="+"):
            Set_calc(c,col,row,"+ ",d1,d2)
        #In case of subtraction
        elif(ope=="-"):
            #Do not handle negative values
            if(d1<d2):
                tmp=d1
                d1=d2
                d2=tmp
            Set_calc(c,col,row,"- ",d1,d2)
        #For multiplication
        elif(ope=="x"):
            Set_calc(c,col,row,"× ",d1,d2)
        else:
            print("[Error] Not support operation:",ope)
    c.showPage()

#Below is the main function
print(" >>> Start")
c = canvas.Canvas("calc_train.pdf",pagesize=A4)

#Addition (maximum value of each element: 99)
Make_page(c,"+",99,99)
#Subtraction (maximum element values: 99 and 9)
Make_page(c,"-",99,9)
#Subtraction 2 (Maximum value of each element: 99)
Make_page(c,"-",99,99)
#Multiplication (maximum element values: 99 and 9)
Make_page(c,"x",99,9)
c.save()

print(" >>> Finish")

When the above sample is executed, 5x5 calculation formulas will be output on A4 size paper. Please modify the calculation range according to your child's grade and adjust the number of calculation formulas per sheet.

image003.png

that's all. Thank you for your hard work.

Recommended Posts

Make a math drill print
Make a squash game
Make a function decorator
Make a distance matrix
I'll make a password!
Make a Nyan button
Make a Tetris-style game!
Make a Base64 decoder
Let's easily make a math gif using Google Colaboratory
Let's make a Discord Bot.
Make a Blueqat backend ~ Part 1
Make a Blueqat backend ~ Part 2
[Django] Make a pull-down menu
Make a LINE BOT (chat)
Make a bookmarklet in Python
Make a fortune with Python
Make Responder a daemon (service)
Let's make a rock-paper-scissors game
How to make a Japanese-English translation
Let's make a remote rumba [Software]
Make a Tweet box for Pepper
Let's make a GUI with python.
Let's make a spot sale service 2
Make a face recognizer using TensorFlow
How to make a slack bot
Let's make a spot sale service 1
How to make a crawler --Advanced
How to make a recursive function
Make C compilation a little easier
python / Make a dict from a list.
[Python] Make the function a lambda function
Make a recommender system with python
How to make a deadman's switch
[Blender] How to make a Blender plugin
Make Flask a Cloud Native application
Make a filter with a django template
Let's make a graph with python! !!
Let's make a supercomputer with xCAT
How to make a crawler --Basic
Make a model iterator with PySide
Make a nice graph with plotly
Make a curtain generator in Blender
Let's make a spot sale service 3