Embercode
✕
ArraysQuick quiz

Partition and product

8 questions. Covers Product except self in Python.

Questions 1 to 5 of 8

  1. 1. The sort_colours function below groups a list of 0s, 1s and 2s in one pass. What does this print? ``python def sort_colours(nums): low = mid = 0 high = len(nums) - 1 while mid <= high: if nums[mid] == 0: nums[low], nums[mid] = nums[mid], nums[low] low += 1 mid += 1 elif nums[mid] == 1: mid += 1 else: nums[mid], nums[high] = nums[high], nums[mid] high -= 1 nums = [2, 1, 0, 2, 0] sort_colours(nums) print(nums) ``
  2. 2. The product_except_self function below returns, for each index, the product of all the other values. What does this print? ``python def product_except_self(nums): n = len(nums) result = [0] * n prefix = 1 for i in range(n): result[i] = prefix prefix *= nums[i] suffix = 1 for i in range(n - 1, -1, -1): result[i] *= suffix suffix *= nums[i] return result print(product_except_self([3, 0, 2, 5])) ``
  3. 3. This version of product_except_self has one change in its second loop. What does print(wrong_equals([2, 3, 4])) print? ``python def wrong_equals(nums): n = len(nums) result = [0] * n prefix = 1 for i in range(n): result[i] = prefix prefix *= nums[i] suffix = 1 for i in range(n - 1, -1, -1): result[i] = suffix suffix *= nums[i] return result ``
  4. 4. Put the steps of product_except_self in the order the function runs them.

    Use the arrows to put the steps in order.

    1. 1.Walk from left to right, storing the running product in result[i] and then multiplying it by nums[i]
    2. 2.Walk from right to left, multiplying result[i] by the running suffix and then multiplying the suffix by nums[i]
    3. 3.Return result, a new list, so nums has not changed
    4. 4.Create result as a new list of zeros with the same length as nums, and start the running product at 1
  5. 5. Put the steps of the check against sorted() from the partition lesson in the order they run.

    Use the arrows to put the steps in order.

    1. 1.Make a sorted copy of the list with sorted()
    2. 2.Compare the two with == and count any mismatch
    3. 3.Run sort_colours on the original list
    4. 4.Make a random list with random.Random(42) and a length from 0 to 12

3 question(s) left on this page.