ProgrammingHardTCS NQT · Accenture

What is printed?

What is printed?
def content(g, s):
    g.sort(); s.sort()
    i = j = 0
    while i < len(g) and j < len(s):
        if s[j] >= g[i]:
            i += 1
        j += 1
    return i
print(content([1, 2, 3], [1, 1]), content([10, 9, 8, 7], [5, 6, 7, 8]))
  1. A. 2 2
  2. B. 1 2
  3. C. 1 1
  4. D. 0 2

Correct answer: B. 1 2

Sorting both lists and giving each child the smallest cookie that satisfies them is the correct greedy. Only one child is satisfied in the first case and two in the second.

More Python Programming questions

Exams that ask this topic