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

Counters | Python Methods and Functions | String Variables

Examples:

 Input: abbaab Output: NO The two halves contain the same characters but their frequencies do not match so they are NOT CORRECT Input: abccab Output: YES 

This problem already exists, see

# Function to check if both halves
# the string contains the same character set

from collections import Counter

 

def checkTwoHalves ( input ):

  

  length = len ( input )

 

# Split input string into two

if (length % 2 ! = 0 ):

first = input [ 0 : length / 2 ]

second = input [(length / 2 ) < code class = "keyword"> + 1 :]

else :

  first = input [ 0 : length / 2 ]

second = input [length / 2 :]

 

  # Convert both halves to a dictionary and compare

  if Counter (first) = = Counter (second):

print 'YES'

  else :

print 'NO'

  
# Driver program

if __ name__ = = "__ main__" :

input = 'abbaab'

  checkTwoHalves ( input )

Output:

 NO 




Tutorials