ProgrammingHardAmazon OA · Flipkart coding round
Which loop builds a list of n items in total O(n^2) time in CPython, because each step copies the whole list?
- A. lst.extend([x]) inside the loop
- B. lst += [x] inside the loop
- C. lst = lst + [x] inside the loop, which creates a new list every step
- D. lst.append(x) inside the loop
Correct answer: C. lst = lst + [x] inside the loop, which creates a new list every step
lst = lst + [x] builds a new list with all previous items each time, so the copying adds up to about n^2 / 2 element copies. append and += on a list extend it in place, which is amortised O(1) per item.
More Python Programming questions
- What is printed? python s = {1, 2, 3} s |= {3, 4} s.discard(9) print(sorted(s), 4 in s, len(s))
- What is printed? python nums = [5, 3, 8] nums2 = nums nums += [1] nums3 = nums[:] nums3.pop() print(nums2, nums3)
- What is printed? python from math import gcd print(gcd(0, 5), gcd(-4, 6), gcd(0, 0))
- What is printed? python x = 12 x //= 5 y = 12 y /= 5 print(x, y, type(x).name, type(y).name)
- What is printed? python import itertools print(list(itertools.islice(itertools.cycle('ab'), 5)), list(itertools.repeat(7, 2)))
- What is printed? python def f(): yield 1 yield 2 print(sum(f()), max(f()), list(zip(f(), f())))