Data Structures & AlgorithmsHardAmazon · Microsoft OA
Edge case: changing a dict while iterating over it.
Edge case: changing a dict while iterating over it.
d = {1: 'a', 2: 'b', 3: 'c'}
try:
for k in d:
if k == 2: d[4] = 'd'
print("ok", len(d))
except Exception as e:
print(type(e).__name__)What is printed?- A. ok 4
- B. ok 3
- C. KeyError
- D. RuntimeError
Correct answer: D. RuntimeError
Adding a key changes the dictionary's size during iteration, and Python raises RuntimeError ('dictionary changed size during iteration'). Iterate over list(d) when you need to modify the dict.
More Coding Interview Problems questions
- Edge case: Python's round() and sorting strings with mixed case. python print(round(2.5), round(3.5), round(-0.5), sorted(['b', 'A', 'a'…
- Problem: Shops sit on a circular ring with profits p = [5, -3, 5, 4, -8, 6]. Choose a contiguous arc of at least one shop (the arc may…
- Problem: Nine nodes 0..8 start disconnected. Apply these unions in order (a union of two nodes already in one set does nothing)…
- Problem: How many prime numbers are there that are less than or equal to 10^6?
- Problem: Let phi(k) be Euler's totient (the count of integers g in [1, k] with gcd(g, k) = 1). What is phi(1) + phi(2) + ... + phi(10)?
- Problem: Count the integers x with 1 <= x <= 1000 whose decimal digits sum to exactly 10.