ProgrammingHardProduct-company MCQ pattern
Which of these is the best way to build a string from n pieces in CPython, and why?
- A. Repeated s += piece, because CPython always resizes the string in place so the total cost is O(n)
- B. Repeated s = ''.join([s, piece]), because join is O(1) amortized
- C. Repeated str.format calls inside the loop, because format avoids copying the existing string
- D. Collecting the pieces in a list and calling ''.join(pieces) once, because it copies each piece once for O(total length)
Correct answer: D. Collecting the pieces in a list and calling ''.join(pieces) once, because it copies each piece once for O(total length)
join computes the total length first and copies each piece once, so the total work is linear in the output length. Repeated += copies the existing text each time unless CPython's in-place optimisation applies, and that optimisation is an implementation detail, not a guarantee.
More Python Programming questions
- A program makes 10^5 membership checks of the form x in visited, where visited holds 10^5 items. Which statement is correct?
- What is printed? python def cnt(a, k): p, l, res = 1, 0, 0 for r, x in enumerate(a): p = x while l <= r and p >= k: p //= a[l] l += 1 res…
- What is printed? python g = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] n, m = 3, 3 P = [[0] (m + 1) for in range(n + 1)] for i in range(n): for j…
- What is printed? python 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…
- What is printed? python from collections import deque def zeroone(n, edges, src): adj = [[] for in range(n)] for u, v, w in edges…
- What is printed? python from collections import deque def ladder(begin, end, words): S = set(words) q = deque([(begin, 1)]) seen = {begin}…