ProgrammingHardGATE CS · Product-company placement
What is printed?
What is printed?
nums = [4, -1, 3, -1, 2] print(sorted(nums, key=lambda v: (v < 0, -v)), sorted(set(nums), reverse=True)[:2])
- A. [-1, -1, 2, 3, 4] [4, 3]
- B. [4, 3, 2, -1, -1] [4, 3, 2]
- C. [2, 3, 4, -1, -1] [4, 3]
- D. [4, 3, 2, -1, -1] [4, 3]
Correct answer: D. [4, 3, 2, -1, -1] [4, 3]
Tuple keys sort first by v < 0 (False before True, so non-negatives first), then by -v, i.e. descending value within each group.
More Python Programming questions
- What is printed? python def walk(d, depth=0): out = [] for k, v in d.items(): out.append(f"{k}{depth}") if isinstance(v, dict): out +=…
- What is printed? python def hanoi(n): return 0 if n == 0 else 2 hanoi(n - 1) + 1 def calls(n): return 1 if n == 0 else 1 + 2 calls(n - 1)…
- What is printed? python import sys def depth(n): try: return depth(n + 1) except RecursionError: return n d = depth(0) print(d > 500, d <…
- What is printed? python x = 0 def a(): global x x = 1 def b(): global x x += 10 b() return x print(a(), x)
- What is printed? python class A: n = [] m = 0 a, b = A(), A() a.n.append(1) a.m += 1 b.n = [2] print(A.n, A.m, a.n, b.n, a.m, b.m)
- What is printed? python x = [0, 1, 2, 3, 4, 5] print(x[1::2], x[-1::-2], x[::-1][::2] == x[::-2])