ProgrammingHardTCS NQT · Accenture

What is printed?

What is printed?
def splits(a):
    total = sum(a)
    s = 0
    c = 0
    for x in a[:-1]:
        s += x
        if 2 * s == total:
            c += 1
    return c
print(splits([1, 2, 1, 0, 2]), splits([0, 0, 0]))
  1. A. 2 2
  2. B. 1 1
  3. C. 1 2
  4. D. 0 2

Correct answer: C. 1 2

A split works when the prefix sum is exactly half the total. For [1,2,1,0,2] the total 6 gives one split, and for [0,0,0] every split works, so the count is 2.

More Python Programming questions

Exams that ask this topic