Embercode
✕
Divide and ConquerQuick quiz

Majority and subarray in Python

6 questions. Covers Majority element and max subarray in Python.

Questions 1 to 5 of 6

  1. 1. What does this program print? ``python def majority(nums, lo, hi): if lo == hi: return nums[lo] mid = lo + (hi - lo) // 2 left = majority(nums, lo, mid) right = majority(nums, mid + 1, hi) if left is not None and left == right: return left need = (hi - lo + 1) // 2 + 1 if left is not None and count_in(nums, lo, hi, left) >= need: return left if right is not None and count_in(nums, lo, hi, right) >= need: return right return None def count_in(nums, lo, hi, value): return nums[lo:hi + 1].count(value) def majority_of(nums): return majority(nums, 0, len(nums) - 1) a = [7, 7, 3, 7, 3, 3, 3, 7] print('A:', majority_of(a)) b = [4, 4, 1, 4, 1, 2, 4] print('B:', majority_of(b)) c = [9, 9, 5, 9, 5, 5, 5] print('C:', majority_of(c)) ``
  2. 2. What does this program print? ``python a = [2, -1, 3, -2] mid = 1 total = 0 best_left = float('-inf') for i in range(mid, -1, -1): total += a[i] best_left = max(best_left, total) total = 0 best_right = float('-inf') for j in range(mid + 1, len(a)): total += a[j] best_right = max(best_right, total) print(f'{best_left} + {best_right} = {best_left + best_right}') ``
  3. 3. Why does majority call count_in on left and right before it returns either one?
  4. 4. For [5, -1, 5], what does a method return if it takes only the best of the two halves and never checks runs that cross the middle?
  5. 5. This version skips the count and returns the left candidate straight away. Which input shows the bug? ``python def majority_pick(nums, lo, hi): if lo == hi: return nums[lo] mid = lo + (hi - lo) // 2 left = majority_pick(nums, lo, mid) right = majority_pick(nums, mid + 1, hi) if left is not None: return left return right ``

5 question(s) left on this page.