Data Structures & AlgorithmsHardAmazon · Microsoft OA
Edge case: itertools.groupby on unsorted data.
Edge case: itertools.groupby on unsorted data.
from itertools import groupby data = "aabbbaacc" print([(k, len(list(g))) for k, g in groupby(data)], len(list(groupby(sorted(data)))))What is printed?
- A. [('a', 2), ('b', 3), ('a', 2), ('c', 2)] 3
- B. [('a', 4), ('b', 3), ('c', 2)] 3
- C. [('a', 2), ('b', 3), ('a', 2), ('c', 2)] 4
- D. [('a', 4), ('b', 3), ('c', 2)] 4
Correct answer: A. [('a', 2), ('b', 3), ('a', 2), ('c', 2)] 3
groupby groups only CONSECUTIVE equal items, so 'a' appears as two separate groups. Sorting first (or using Counter) gives one group per distinct value: 3.
More Coding Interview Problems questions
- Problem: Row n of Pascal's triangle built in place, plus two checks. python def row(n): r = [1] for in range(n): r = [1] + [r[i] + r[i+1]…
- Problem: Find the maximum sum of a sub-rectangle whose sum does not exceed k (fix two columns, then 'max subarray sum ≤ k' with a sorted…
- Problem: What does the following print? It is the multiplicative inverse of 7 modulo 26. python print(pow(7, -1, 26))
- Problem: How many trailing zeros does 100! have? Run the code that counts factors of 5. python n = 100 c = 0 p = 5 while p <= n: c += n //…
- Problem: Starting from 27, the Collatz map is n -> n/2 if n is even and n -> 3n+1 if n is odd. How many steps does it take to first reach…
- Problem: Find the smallest positive integer n such that n! has at least 6 trailing zeros. Run the code. python def zeros(n): c = 0 p = 5…