Write a python program to count the number of palindrome strings that occurred in the given string.
Question
Write a python program to count the number of palindrome strings that occurred in the given string.
Solution
Sure, here is a Python program that counts the number of palindrome strings in a given string:
def count_palindromes(s):
count = 0
for i in range(len(s)):
for j in range(i+1, len(s)+1):
if s[i:j] == s[i:j][::-1]:
count += 1
return count
# Test the function
s = "madam arora teaches malayalam"
print(count_palindromes(s))
In this program, we define a function count_palindromes(s)
that takes a string s
as input. We initialize a counter count
to 0. Then we iterate over all substrings of s
using two nested loops. For each substring, we check if it is equal to its reverse (which means it's a palindrome), and if so, we increment the counter. Finally, we return the counter.
The test case "madam arora teaches malayalam" should return 18, as there are 18 palindromic substrings in this string.
Similar Questions
Write a Python program to count the number of occurrences of a specific character in a string
Write a python program to print the number of occurrences of a substring into a line
A palindrome is a string whose reversal is identical to the string. How many bitstrings of length n are palindromes?
Read a string with words separated by space and return its length and count of consonants.Sample Inputwrite a programSample Output158
Write a program to count number of words in a given string whose length is greater than 3.For example:Input Resultpython is easier than C3
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.