Count Occurrence of Word and Palindrome in String Python

In this class, we write a program to count occurrence of word and palindrome in string python.

For Complete YouTube Video: Click Here

Count Occurrence of Word

Q1) Write a program to count the occurrence of a word in the given string.

Example:

x=”hello how are you hello”

word = “hello”

Count how many times the word hello present in the string.

Output: 2

The logic we discuss here will work only on some of the strings.

In our previous class, we discussed how to find the number of words in a given string.

Reader, please watch the previous and try to write your code to full fill the failure situations. Failure examples are explained below.

We can solve the problem by using inbuilt python methods easily.

We intend to improve the coding skill of the reader.

Try to write it using loops and conditions.

Example:

Failure case

x=”sssss ssss”

word = “sss”

Here we have to identify the word sss present in the string or not?

Our logic which we discuss will say yes, it’s present. But the word sss, not present.

Logic

Loop on the string character by character.

At each character position, try to check the word that needs to occur is present are not.

For this, we need a nested loop.

The outer loop is used to loop on a given string.

The inner loop is used to loop on a given word. and check the characters matching.

Analyze the code given below. And write the code to full fill the missing logic.

Program

string = input("enter your string")
word=input("enter your word")
strlength=len(string)
wordlength=len(word)
i=0
count=0
while(i<=(strlength-wordlength)):
    found=1
    j=0
    while(j<wordlength):
        if(string[i+j]!=word[j]):
            found=0
            break
        j+=1
    if found==1:
        count+=1
    i+=1
print(count)

The string is Palindrome or Not.

Q2) Write a program to check the given string is palindrome or not?

If the reverse of the string is equal to the actual string. We say the string is a palindrome.

Example:

x=”madam”

If we reverse the above string, we will get the exact string, madam.

The above example is a palindrome.

Logic

Check the first and last characters in the given string are equal or not.

If the last and first characters are equal. Continue to check the second character from start and end.

If equal. Continue with the third character. so on

To implement the logic, we are using two variables i and j.

the variable i is used to moving from the beginning. And variable j is used to move from the ending.

When variable i cross j means all characters over.

Check the program given below. And identify the logic for better practice.

Program

string=input("enter the string")
string=string.casefold()
length=len(string)
i=0
j=length-1
while i<=j:
    if(string[i]==string[j]):
        pass
    else:
        break
    i+=1
    j-=1
if(i>j):
    print("palindrome")
else:
    print("Not Palindrome")