Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

MAINT Improve build of exercises to avoid duplicated 'Write your code here' cells #788

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 26 additions & 2 deletions build_tools/generate-exercise-from-solution.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@
from jupytext.myst import myst_to_notebook
import jupytext


WRITE_YOUR_CODE_COMMENT = "# Write your code here."


def replace_simple_text(input_py_str):
result = input_py_str.replace("📃 Solution for", "📝")
return result
Expand Down Expand Up @@ -36,7 +40,24 @@ def remove_solution(input_py_str):
marker in c["source"]]

for c in cells_to_modify:
c["source"] = pattern.sub("# Write your code here.", c["source"])
c["source"] = pattern.sub(WRITE_YOUR_CODE_COMMENT, c["source"])

previous_cell_is_write_your_code = False
all_cells_before_deduplication = nb.cells
nb.cells = []
for c in all_cells_before_deduplication:
if c["cell_type"] == "code" and c["source"] == WRITE_YOUR_CODE_COMMENT:
current_cell_is_write_your_code = True
else:
current_cell_is_write_your_code = False
if (
current_cell_is_write_your_code
and previous_cell_is_write_your_code
):
# Drop duplicated "write your code here" cells.
continue
nb.cells.append(c)
previous_cell_is_write_your_code = current_cell_is_write_your_code

# TODO: we could potentially try to avoid changing the input file jupytext
# header since this info is rarely useful. Let's keep it simple for now.
Expand All @@ -45,6 +66,7 @@ def remove_solution(input_py_str):


def write_exercise(solution_path, exercise_path):
print(f"Writing exercise to {exercise_path} from solution {solution_path}")
input_str = solution_path.read_text()

output_str = input_str
Expand All @@ -59,7 +81,9 @@ def write_all_exercises(python_scripts_folder):
for solution_path in solution_paths:
exercise_path = Path(str(solution_path).replace("_sol_", "_ex_"))
if not exercise_path.exists():
print(f"{exercise_path} does not exist")
print(
f"{exercise_path} does not exist, generating it from solution."
)

write_exercise(solution_path, exercise_path)

Expand Down
Loading