Program to check whether String Halves Are Alike in Python

PythonServer Side ProgrammingProgramming

Suppose we have a string s whose length is even. We have to split this string into two different halves of same lengths. So consider 'a' is the first half and 'b' is the second half. We say two strings are alike when they have the same number of vowels (uppercase or lowercase). We have to check whether 'a' and 'b' are alike or not.

So, if the input is like s = "talent", then the output will be True because two halves are "tal" and "ent", they are alike because they have only one vowel and two consonants.

To solve this, we will follow these steps −

  • a := left half of s

  • b := right half of s

  • count1 := 0, count2 := 0

  • for each c in a, do

    • if c is a vowel, then

      • count1 := count1 + 1

  • for each c in b, do

    • if c is a vowel, then

      • count2 := count2 + 1

  • return true if count1 is same as count2, otherwise false

Example (Python)

Let us see the following implementation to get better understanding −

 Live Demo

def solve(s):
   vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']

   a = s[:len(s)//2]
   b = s[len(s)//2:]

   count1 = 0
   count2 = 0

   for c in a:
      if c in vowels:
         count1 += 1
   for c in b:
      if c in vowels:
         count2 += 1

   return count1 == count2

s = "talent"
print(solve(s))

Input

"talent"

Output

True
raja
Published on 18-May-2021 11:44:18
Advertisements