Homework class

class Homework(filename=None)

Formats and exports homework answers as LaTeX commands or Gradescope strings.

Parameters:

filename (str, optional) – Default filename for LaTeX output. Defaults to None.

Attributes

filename: str

File name for the LaTeX output file.

latex_answers: dict

Dictionary for storing answers as LaTeX \newcommand definitions.

Methods

add_latex_answer(name, value, precision=4)

Adds an answer as a LaTeX \newcommand entry to latex_answers. String values are stored as-is. Numeric values are rounded and formatted with the specified number of decimal places.

Parameters:
  • name (str) – Name of the LaTeX command. Must conform to LaTeX naming conventions (letters only, no numbers or symbols).

  • value (str or numeric) – Answer to be stored.

  • precision (int, optional) – Number of decimal places for numeric values. Defaults to 4.

Returns:

None

gs_answer(value, tolerance=8, precision=2)

Returns a Gradescope-compatible formatted answer string of the form '[____](=value+-tolerance)'.

Parameters:
  • value (str or numeric) – Answer to format.

  • tolerance (float, optional) – Numeric tolerance for grading. Defaults to 8.

  • precision (int, optional) – Number of decimal places for rounding numeric values. Defaults to 2.

Returns:

A Gradescope-compatible formatted string.

Return type:

str

write_answer_file(filename)

Writes all stored answers to a LaTeX file as \newcommand definitions. Appends .tex to the filename if it is not already present.

Parameters:

filename (str) – Destination file path.

Returns:

None