ProgrammingHardAmazon OA · Flipkart coding round
A program builds a long output string with `s = s + str(i) + ' '` for each of n = 2 * 10^5 values i. Which change is the standard fix for Python?
- A. Replace str(i) with repr(i) for each piece
- B. Use s += in a nested loop so Python reuses the buffer
- C. Convert the whole string to a bytearray before each addition
- D. Collect the pieces in a list and call ' '.join(parts) once at the end
Correct answer: D. Collect the pieces in a list and call ' '.join(parts) once at the end
Building an immutable str by repeated concatenation can copy the whole string each time, which is quadratic in the worst case. Appending to a list and joining once is linear.
More Python Programming questions
- What is printed? python rows = [('bob', 90), ('amy', 90), ('cat', 75)] rows.sort(key=lambda r: (-r[1], r[0])) print([r[0] for r in rows])
- What is printed? python print([1, 2] < [1, 2, 0], (1, 2) < (1, 2, 0), 'abc' < 'abd', [2] < [1, 9])
- What is printed? python x = [1, 2, 3, 4] y = x x = x + [5] x.append(6) y.append(9) print(len(x), len(y), y is x)
- What is printed? python from collections import Counter c = Counter([3, 1, 3, 2, 1, 3]) print(c.mostcommon(1), sorted(c.elements()), c[7])
- What is printed? python from math import comb print(comb(5, 2), comb(5, 7), comb(0, 0), comb(3, 1) comb(3, 1))
- What is printed? python x = 0 total = 0 for i in range(1, 6): if i % 2: continue x += i if x > 4: break else: total = -1 print(x, total)