16 — Practice solutions
These are independently written explanations, not an official marking scheme.
16A
Slices: "OMP", "ING", "CMUIG".
def count_vowels(text):
count = 0
for character in text.lower(): # One comparison rule handles either case.
if character in "aeiou":
count += 1
return countlower() supplies a new string for traversal; the original argument is unchanged.
Reasoning
Write the index row first, then select positions using the excluded stop and step. For vowels, case-normalise for comparison; count occurrences rather than distinct vowels.
"AA"contributes2, not1.
16B
def write_totals(source_path, output_path):
total = 0
with open(source_path, "r", encoding="utf-8") as source:
for line in source:
if line.strip() != "": # A blank line is not a numeric record.
total += int(line)
with open(output_path, "w", encoding="utf-8") as output:
output.write(str(total) + "\n") # write() does not add a newline itself.An empty source produces 0 followed by a newline. Using append mode would retain old results, contrary to “replacing”.
Reasoning
The task replaces output, so mode is
w, nota. Blank lines must be excluded before integer conversion. Sum starts at 0 because an empty file has no contributions. Reading all input before opening output also avoids truncating the source early if the same path is accidentally supplied.