ProgrammingHardProduct-company MCQ pattern
Which call builds one string from n pieces in O(total length) time?
- A. sum(pieces, '')
- B. functools.reduce(lambda a, b: a + b, pieces, '')
- C. a loop that does s = s + p for each piece p
- D. ''.join(pieces)
Correct answer: D. ''.join(pieces)
join sums the lengths first and copies each piece once. sum() refuses a string start value with a TypeError, and repeated + copies the growing result each time, which is O(n squared) in the worst case.
More Python Programming questions
- Which statement about sorting in Python is correct?
- What is printed? python print(oct(-8), hex(-255), bin(0), format(-5, 'b'))
- What is printed? python n = 13 print(n ^ (n >> 1), [bin(i ^ (i >> 1)) for i in range(4)])
- What is printed? python print(~5 == -6, ~(-5) == 4, (-5) >> 1 == -2, -5 // 2 == -3)
- What is printed? python import unicodedata print(unicodedata.normalize('NFC', 'eu0301') == 'é', len(unicodedata.normalize('NFD', 'é'))…
- What is printed? python print('a1'.isalnum(), '١'.isalnum(), ' '.isspace(), ''.isspace(), 'u00a0'.isspace())