Check if both halves of the string have the same set of characters in Python


We have to check whether two halves of a string have the same set of characters or not in Python. The frequency of the characters in the two halves must be identical. If the length of the string is odd, ignore the middle and check for the remaining characters. Follow the below steps to write code for the program.

Algorithm

1. Initialize a string.
2. Initialize an empty dictionary variable alphabets.
3. Initialize a variable mid with length / 2.
4. Write a loop until mid element.
   4.1. Initialize the corresponding dictionary item by alphabets[char] with one if it's not
initialized.
   4.2. If it's already initialized, increment the count by 1.
5. Run the loop from the mid element to the last item.
   5.1. Check if the char is in the dictionary or not.
      5.1.1. Decrement the count of char by one if it's in the dictionary
6. Run a loop over the dictionary alphabets.
   6.1. If you find any item with more than 0 value.
      6.1.1. Print **No!**.
   6.2. Else print Yes!

Let's write the code.

Example

## initializing the string
string = "aabccbaa"
## initializing an empty string
alphabets = {}
## initializing the mid variable
mid = len(string) // 2
## loop to count the frequency of char in the first half
for i in range(mid):
   ## setting the value of char count to 1 if it's not in the dictionary
   if not alphabets.get(string[i], 0):
      alphabets[string[i]] = 1
   else:
      ## incrementing the count of char by 1 if it's already initialized
      alphabets[string[i]] += 1
## loop to decrement the count of char by 1 if it's present in second half of the string
for i in range(len(string) - 1, mid - 1, -1):
   ## checking whether the char is in second half or not
   if alphabets.get(string[i], 0):
   ## if it's present, decrementing the count by 1
   alphabets[string[i]] -= 1
## initializing a flag variable for the track
flag = 1
## loop to check the values after decrementing
for i in alphabets.values():
## checking for zeroes
if i != 0:
   ## if it's not zero breaking the loop and printing No!
   print("No!")
   ## setting 0 for track
   flag = 0
   break
## if flag value still 1 then, it's Yes!
if flag == 1:
   ## printing Yes!
   print("Yes!")

Output

If you run the above program, you will get the following output.

Yes!

Conclusion

If you have any doubts regarding the tutorial, mention them in the comment section.

Updated on: 23-Oct-2019

74 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements