python生成PDFファイル20以内加減算法は、小学校に通う赤ちゃんに



# -*- coding: utf-8 -*-
import random
from reportlab import platypus
from reportlab.lib.units import inch 
from reportlab.lib.pagesizes import A4, landscape #         PDF
from reportlab.lib import colors


def genList():
    ret = set()

    while True:
        a = random.randint(1, 20)
        b = random.randint(1, 20)
        c = random.randint(1, 20)
        if a + b + c <= 20 and (a > 10 or b > 10 or c > 10):
            ret.add( '%-2d + %-2d + %-2d =' % (a, b, c) )
        if len(ret) == 25: break

    while True:
        a = random.randint(1, 20)
        b = random.randint(1, 20)
        c = random.randint(1, 20)
        if a + b <= 20 and a + b - c >= 0 and (a > 10 or b > 10 or c > 10):
            ret.add( '%-2d + %-2d - %-2d =' % (a, b, c) )
        if len(ret) == 50: break

    while True:
        a = random.randint(1, 20)
        b = random.randint(1, 20)
        c = random.randint(1, 20)
        if a - b >= 0 and a - b + c <= 20 and (a > 10 or b > 10 or c > 10):
            ret.add( '%-2d - %-2d + %-2d =' % (a, b, c) )
        if len(ret) == 75: break

    while True:
        a = random.randint(11, 20)
        b = random.randint(1, 20)
        c = random.randint(1, 20)
        if a - b - c >= 0 and (a > 10 or b > 10 or c > 10):
            ret.add( '%-2d - %-2d - %-2d =' % (a, b, c) )
        if len(ret) == 100: break

    ret = list(ret)
    random.shuffle(ret)
    return ret

'''for i in genList():
    print i'''

def genTable():
    data = []
    items = genList()
    for i in range(0, len(items), 5):
        data.append(items[i:i+5])
    # Courier   reportlab          
    # (0,0)/(-1,-1)   style    ,      
    tablestyle = [('FONT', (0,0), (-1,-1), 'Courier', 12),
                  ('LINEAFTER', (0,0), (-2,-1), 1, colors.black)]
    return platypus.Table(data, 2.2*inch, 0.35*inch, tablestyle)

import sys
try:
    n = int(sys.argv[1]) #  ,       PDF
except:
    n = 1
try:
    fname = sys.argv[2]
except:
    fname = '20plus100.pdf'

doc = platypus.SimpleDocTemplate(fname, topMargin=0.5*inch, bottomMargin=0.5*inch, title='DaDa Math', author='qyb')

elements = []
for i in range(n):
    elements.append(genTable())
    elements.append(platypus.flowables.PageBreak())

doc.pagesize = landscape(A4)
doc.build(elements)




この機能はpythonのreportlabパッケージを使用する必要があります.インストールをダウンロードしてください.