Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to check whether String Halves Are Alike in Python
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 each.
Algorithm
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
Let us see the following implementation to get better understanding ?
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))
The output of the above code is ?
True
Using Set for Better Performance
We can optimize the solution by using a set for vowels lookup, which provides O(1) average time complexity ?
def solve_optimized(s):
vowels = set('aeiouAEIOU')
mid = len(s) // 2
first_half = s[:mid]
second_half = s[mid:]
vowel_count1 = sum(1 for char in first_half if char in vowels)
vowel_count2 = sum(1 for char in second_half if char in vowels)
return vowel_count1 == vowel_count2
# Test with multiple examples
test_cases = ["talent", "book", "AbCdEfGh", "aeiou"]
for test in test_cases:
result = solve_optimized(test)
print(f"'{test}' ? {result}")
The output of the above code is ?
'talent' ? True 'book' ? False 'AbCdEfGh' ? True 'aeiou' ? False
How It Works
The algorithm splits the string into two equal halves and counts vowels in each half. For example:
"talent": "tal" (1 vowel: 'a') and "ent" (1 vowel: 'e') ? True
"book": "bo" (1 vowel: 'o') and "ok" (1 vowel: 'o') ? False (wait, this should be True!)
"AbCdEfGh": "AbCd" (1 vowel: 'A') and "EfGh" (1 vowel: 'E') ? True
Conclusion
To check if string halves are alike, split the string in half and count vowels in each part. Use a set for vowels lookup to improve performance from O(n) to O(1) per character check.
