5. Decimals python๏
The python below requires the following .tex files:
1"""
2Module of functions to return decimals dictionary for LaTeX
3"""
4import random
5
6
7def get_add_sub_dec_dict(nump, numip, numdp):
8 if nump is None or nump == 3:
9 nump = random.randint(1, 2)
10 match nump:
11 case 1:
12 return add_dict(numip, numdp)
13 case 2:
14 return sub_dict(numip, numdp)
15
16
17def add_dict(numip, numdp):
18 # na + nb = nc
19 # Generate a random decimal number between 0.00001 and 9999
20 na = random.uniform(10**-numdp, (10**numip)-0.1)
21 nb = random.uniform(10**-numdp, (10**numip)-0.1 - na)
22 # Format the result to 1,2 or 3 decimal places
23 format_string = "{:." + str(numdp) + "f}"
24 na = format_string.format(na)
25 nb = format_string.format(nb)
26 nc = float(na) + float(nb)
27 nc = format_string.format(nc)
28 kv = dict()
29 kv["num1"] = f"{na}"
30 kv["num2"] = f"{nb}"
31 kv["process"] = "+"
32 kv["answer"] = f"{nc}"
33 return kv
34
35
36def sub_dict(numip, numdp):
37 # na + nb = nc
38 # Generate a random decimal number between 0.01 and 100
39 nc = random.uniform(10**-numdp, (10**numip)-0.1)
40 nb = random.uniform(10**-numdp, (10**numip)-0.1- nc)
41 # Format the result to 1,2 or 3 decimal places
42 format_string = "{:." + str(numdp) + "f}"
43 nc = format_string.format(nc)
44 nb = format_string.format(nb)
45 na = float(nc) + float(nb)
46 na = format_string.format(na)
47 #
48 kv = dict()
49 kv["num1"] = f"{na}"
50 kv["num2"] = f"{nb}"
51 kv["process"] = "-"
52 kv["answer"] = f"{nc}"
53 return kv
54
55
56
The Python to create booklets of questions involving the addition and subtraction of decimals, is below.
1from pathlib import Path
2import subprocess
3import time
4import decimals_functions as decf
5
6# import magick_pdf_to_png
7
8
9currfile_dir = Path(__file__).parent
10tex_template_path = currfile_dir / "add_sub_decimals_booklet_template.tex"
11texans_template_path = currfile_dir / "add_sub_decimals_booklet_ans_template.tex"
12tex_diagram_template_path = (
13 currfile_dir / "add_sub_decimals_booklet_diagram_template.tex"
14)
15
16
17def convert_to_pdf(tex_path, currfile_dir, aux_path):
18 """
19 Converts a TeX file to PDF format using pdfLaTeX.
20
21 Args:
22 tex_path (str): The path to the TeX file.
23 currfile_dir (str): The path to the directory where the TeX file is located.
24 aux_path (str): The path to the directory where auxiliary files will be stored.
25
26 Returns:
27 subprocess.CompletedProcess: A subprocess.CompletedProcess object containing information about the completed process.
28
29 Raises:
30 FileNotFoundError: If the TeX file does not exist.
31 subprocess.CalledProcessError: If pdfLaTeX returns a non-zero exit code.
32 """
33 result = subprocess.run(
34 [
35 "pdfLaTeX",
36 tex_path,
37 "-output-directory",
38 currfile_dir,
39 "-aux-directory",
40 aux_path,
41 ],
42 stdout=subprocess.PIPE,
43 )
44
45
46# tex_keys = ["num1", "num2", "process"]
47tex_keys_q = ["answer"]
48
49def make1_diagram(tex_diagram_template_txt, nump, numip, numdp):
50 tex_diagram_template_txt_ans = tex_diagram_template_txt
51 kv = decf.get_add_sub_dec_dict(nump, numip, numdp)
52 posttext = r"\vspace{-2pt}"
53
54 for key, value in kv.items():
55 tex_diagram_template_txt_ans = tex_diagram_template_txt_ans.replace(
56 "<<" + key + ">>", value
57 )
58
59 for key, value in kv.items():
60 if key in tex_keys_q:
61 tex_diagram_template_txt = tex_diagram_template_txt.replace(
62 "<<" + key + ">>", ""
63 )
64 else:
65 tex_diagram_template_txt = tex_diagram_template_txt.replace(
66 "<<" + key + ">>", value
67 )
68 tex_diagram_template_txt = tex_diagram_template_txt.replace("<<numip>>", str(numip))
69 tex_diagram_template_txt = tex_diagram_template_txt.replace("<<numdp>>", str(numdp))
70 tex_diagram_template_txt_ans = tex_diagram_template_txt_ans.replace("<<numip>>", str(numip))
71 tex_diagram_template_txt_ans = tex_diagram_template_txt_ans.replace("<<numdp>>", str(numdp))
72 # return tex_diagram_template_txt
73 return tex_diagram_template_txt + posttext, tex_diagram_template_txt_ans + posttext
74
75
76def get_title(nump):
77 match nump:
78 case 1:
79 return "Addition"
80 case 2:
81 return "Subtraction"
82 case 3:
83 return "Addition and subtraction"
84
85
86def main():
87 nump = input("Enter 1, 2, or 3 for +, -, random for the process \n")
88 if nump.strip().isdigit():
89 nump = int(nump)
90 if not nump in [1, 2, 3]:
91 nump = 3 # random by default
92 else:
93 nump = 3 # random by default
94 # get title for part of heading indicating which process/es
95 title = get_title(nump)
96 #
97 numip = input("Enter 1, 2, 3, or 4 for the number of places before the decimal point \n")
98 if numip.strip().isdigit():
99 numip = int(numip)
100 if not numip in [1, 2, 3, 4, 5]:
101 numip = 1 # 1 by default
102 else:
103 numip = 1 # 1 by default
104 #
105 numdp = input("Enter 1, 2, 3, 4, or 5 for the number of decimal places \n")
106 if numdp.strip().isdigit():
107 numdp = int(numdp)
108 if not numdp in [1, 2, 3, 4, 5]:
109 numdp = 1 # 1 by default
110 else:
111 numdp = 1 # 1 by default
112 #
113 #
114 numq = input("Enter the number of questions from 1 to 100 \n")
115 if numq.strip().isdigit():
116 numq = int(numq)
117 if not numq in range(1, 101):
118 numq = 25 # 25 by default
119 else:
120 numq = 25 # 25 by default
121 #
122 filename = input("Enter the base filename to be added to the prefix asd_: \n")
123 if not filename:
124 filename = "1" # "asd_1_q and asd_1_ans as default file"
125 # set names of files that are made
126 # questions
127 tex_output_path = currfile_dir / f"asdBK_{filename}_q.tex"
128 aux_path = currfile_dir / "temp"
129 # answers
130 tex_output_path_ans = currfile_dir / f"asdBK_{filename}_ans.tex"
131
132 # Read in the LaTeX template file
133 with open(tex_template_path, "r") as infile:
134 tex_template_txt = infile.read()
135 # Read in the LaTeX template file for answers
136 with open(texans_template_path, "r") as infile:
137 tex_template_txt_ans = infile.read()
138 # Read in the LaTeX diagram template file
139 with open(tex_diagram_template_path, "r") as infile:
140 tex_diagram_template_txt = infile.read()
141
142 # <<cols>>
143 # generate column text and column text for answers
144 col1_text = ""
145 col1_text_ans = ""
146 rmax = numq + 1
147 for _ in range(1, rmax):
148 img_tex, img_tex_ans = make1_diagram(tex_diagram_template_txt, nump, numip, numdp)
149 col1_text += img_tex
150 col1_text_ans += img_tex_ans
151
152 # Replace the <<title>> placeholder in the LaTeX template
153 tex_template_txt = tex_template_txt.replace("<<title>>", title)
154 tex_template_txt_ans = tex_template_txt_ans.replace("<<title>>", title)
155 # Replace the <<cols>> placeholder in the LaTeX template with the generated diagrams
156 tex_template_txt = tex_template_txt.replace("<<cols>>", col1_text)
157 tex_template_txt_ans = tex_template_txt_ans.replace("<<cols>>", col1_text_ans)
158
159 # Write the question tex to an output file
160 with open(tex_output_path, "w") as outfile:
161 outfile.write(tex_template_txt)
162
163 # Write the answer tex to an output file
164 with open(tex_output_path_ans, "w") as outfile:
165 outfile.write(tex_template_txt_ans)
166
167 # Wait for the file to be created
168 time.sleep(1)
169 # Convert the LaTeX files to PDFs
170 convert_to_pdf(tex_output_path, currfile_dir, aux_path)
171 convert_to_pdf(tex_output_path_ans, currfile_dir, aux_path)
172
173
174if __name__ == "__main__":
175 print("starting")
176 main()
177 print("finished")