Data Structures & AlgorithmsModerateWipro · Accenture pattern
What is printed? (Python sort stability with a key)
What is printed? (Python sort stability with a key)
recs = [("amit", 82), ("bina", 90), ("chirag", 82), ("dev", 75), ("esha", 90)]
by_score = sorted(recs, key=lambda r: -r[1])
print([n for n, _ in by_score])- A. ['bina', 'esha', 'amit', 'chirag', 'dev']
- B. ['esha', 'bina', 'chirag', 'amit', 'dev']
- C. ['bina', 'esha', 'chirag', 'amit', 'dev']
- D. ['dev', 'amit', 'chirag', 'bina', 'esha']
Correct answer: A. ['bina', 'esha', 'amit', 'chirag', 'dev']
Python's Timsort is stable, so records with equal scores keep their original order: bina before esha, amit before chirag. Sorting with reverse=True would also keep ties in original order. O(n log n).
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- What is printed? (finding the k-th node from the end with two pointers) python vals = [11, 22, 33, 44, 55, 66] def kthend(k): lead = trail…
- What is printed? (C: array passed to a function decays to a pointer) c void f(int a[]) { printf("%zu ", sizeof(a) / sizeof(a[0])); } int…
- What is printed? (balanced brackets with a counter only) python def bycounter(s): c = 0 for ch in s: c += 1 if ch == '(' else -1 if c < 0…
- What is printed? (string rotation check) python def isrot(a, b): return len(a) == len(b) and b in a + a print(isrot("waterbottle"…
- What is printed? (sliding window: count subarrays with product less than k, positive values) python def countprod(a, k): if k <= 1: return…
- What is printed? (Java: == vs equals on Strings) java String a = "hello"; String b = "hel" + "lo"; String c = new String("hello"); String…