Data Structures & AlgorithmsHardTCS NQT Digital · Python semantics
Problem: What does the following print?
Problem: What does the following print?
def add(x, bucket=[]):
bucket.append(x)
return bucket
add(1)
add(2)
print(add(3))- A. [3]
- B. [1, 2, 3]
- C. [1, 2]
- D. [2, 3]
Correct answer: B. [1, 2, 3]
The default list is created once and shared between calls, so all three appends land in the same list. Assuming a fresh list each call is the classic Python trap.
More Coding Interview Problems questions
- Problem: What does the following print for the array [7, 10, 4, 3, 20, 15] with k = 3? python import heapq def kth(a, k): h = [] for x in…
- Problem: What does the following print? python ops = [('b', 2), ('a', 2), ('c', 1), ('d', 3)] print([x for x, in sorted(ops, key=lambda t…
- Problem: Coins of values {1, 5, 6, 9} are available, unlimited copies each. What is the minimum number of coins needed to make exactly 11?
- Problem: In the O(n log n) longest increasing subsequence algorithm, the array tails[k] is maintained over the input. What does tails[k]…
- Problem: A dynamic array doubles its capacity whenever it is full and copies all elements. Which statement about n pushes is correct?
- Problem: How many ways are there to tile a 2 x 10 board completely with 2 x 1 dominoes (placed horizontally or vertically)?