Embercode
✕
LoopsQuick quiz

Off-by-one check

6 questions. Covers Half-open ranges in Python.

Questions 1 to 5 of 6

  1. 1. What does this program print? ``python a = [3, 1, 4, 1, 5, 9, 2, 6] total = 0 for i in range(2, 5): total += a[i] print(total, 5 - 2) ``
  2. 2. What does this program print? ``python word = "forgestack" print(word[4:7]) print(len(word[7:])) ``
  3. 3. A programmer wants the total of the temperatures in the half-open range [1, 3), which means positions 1 and 2. The code below adds the wrong items. What is the bug? ``python temps = [18, 21, 19, 25, 23] total = 0 for i in range(1, 4): total += temps[i] print(total) ``
  4. 4. A page loop should make only three pages for 9 results: [0, 3), [3, 6) and [6, 9). This code also prints an empty page [9, 9) with length 0. ``python total_items = 9 page_size = 3 for start in range(0, total_items + 1, page_size): end = min(start + page_size, total_items) print(f"page [{start}, {end}) length {end - start}") `` Which change fixes it?
  5. 5. Two bookings are half-open ranges, so 9 to 10 and 10 to 11 should not clash. This function says they do clash. Which part is the bug? ``python def overlaps(a_start, a_end, b_start, b_end): return a_start <= b_end and b_start <= a_end ``

5 question(s) left on this page.