ProgrammingVery hardTCS CodeVita · Infosys HackWithInfy
What is printed?
What is printed?
def cnt_pal(s):
n = len(s)
c = 0
for ctr in range(2 * n - 1):
l, r = ctr // 2, ctr // 2 + ctr % 2
while l >= 0 and r < n and s[l] == s[r]:
c += 1
l -= 1
r += 1
return c
print(cnt_pal('aaa'), cnt_pal('abc'))- A. 4 3
- B. 6 3
- C. 6 2
- D. 5 3
Correct answer: B. 6 3
Expanding around each of the 2n - 1 centres counts palindromes. 'aaa' has 3 single letters, 2 pairs and 1 triple, which is 6, and 'abc' has 3 single letters.
More Python Programming questions
- What is printed? python import bisect a = [9, 7, 5, 3, 1] print(bisect.bisectleft(a, -6, key=lambda v: -v), bisect.bisectleft(a, 6…
- What is printed? python from collections import deque d = deque([1, 2, 3, 4, 5], maxlen=5) d.rotate(2) d.appendleft(0) print(list(d)…
- What is printed? python print(max(['bb', 'aa', 'c'], key=len), min(['bb', 'aa', 'c'], key=len))
- What is printed? python from collections import defaultdict words = ['eat', 'tea', 'tan', 'ate', 'nat', 'bat'] g = defaultdict(list) for w…
- What is printed? python print(' a b '.split(' '), ' a b '.split(), 'a b x c d'.split(None, 1))
- What is printed? python from fractions import Fraction x = Fraction(1, 3) + Fraction(1, 6) print(x, x.numerator, Fraction(6, -8))