ProgrammingHardAmazon OA · Flipkart coding round
What is printed?
What is printed?
def maj(a):
cand, cnt = None, 0
for x in a:
if cnt == 0:
cand = x
cnt += 1 if x == cand else -1
return cand
print(maj([2, 2, 1, 1, 1, 2, 2]), maj([1, 2, 3]))- A. 2 1
- B. 2 3
- C. 1 3
- D. 3 2
Correct answer: B. 2 3
Boyer-Moore voting keeps one candidate and a counter. Value 2 occurs four times out of seven and wins, while [1, 2, 3] ends with 3 as the last remaining candidate.
More Python Programming questions
- What is printed? python print(list(dict.fromkeys([3, 1, 3, 2, 1])), sorted(set([3, 1, 3, 2, 1]))[::-1])
- What is printed? python def sortcount(a): if len(a) <= 1: return a, 0 m = len(a) // 2 l, x = sortcount(a[:m]) r, y = sortcount(a[m:]) out…
- What is printed? python print([10, 20][True], [10, 20][False])
- What is printed? python print(repr('ab' -1), [1] 0, 'a' 3 == 'aaa')
- What is printed? python print(all([]), any([]), all([0, 1]), any([0, '']))
- What is printed? python print([3, 1].sort() or 'x', sorted([3, 1]) == [1, 3])