Python program to check if both halves of the string have same set of characters.


Given a string, our task is to check if both halves of the string have the same set of characters or not. To solve this problem we first split the string from the middle, so we get two halves, now we check each halves having the same set of characters or not. If the length of the string is not even then ignore the middle element and check for the rest.

Algorithm

Step 1: Given a string.
Step 2: Break the input string into two parts.
Step 3: Then convert both parts into a dictionary using Counter(iterator) method and each dictionary contains its character as key and frequency as value.
Step 4: Now compare these two dictionaries. Here we use == operator. First we checks keys of both dictionaries are same or not,
then checks for values of each key. If both cases are true then two halves have the same set of characters.

Example Code

from collections import Counter
def checkhalves(input):
   length = len(input)
   if (length % 2 != 0):
      first = input[0:int(length / 2)]
      second = input[(int(length / 2)) + 1:]
   else:
      first = input[0:int(length / 2)]
      second = input[int(length / 2):]
   if Counter(first) == Counter(second):
      print ("Both halves are same")
   else:
      print ("Both halves are not same ")
# Driver program
if __name__ == "__main__":
input = input("Enter The String")
checkhalves(input)

Output

Enter The String abba
Both halves are same

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 23-Jun-2020

157 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements