
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check If Both Halves of the String Have Same Set of Characters in Python
We can split a long string from the middle and check if the two halves are equal or not. The input string may have an odd or even number of characters. If it has an even number of characters, we divide the two halves by taking half of the length. But if the number of characters is odd then we ignore the middlemost character and then compare the remaining two halves.
In the below program we create the two halves of the input string with above logic and then
Example
from collections import Counter def comparehalves(input_string): str_len = len(input_string) # If number of characyes is odd # ignore the middle character if (str_len % 2 != 0): left = input_string[0:int(str_len / 2)] right = input_string[(int(str_len / 2)) + 1:] else: left = input_string[0:int(str_len / 2)] right = input_string[int(str_len / 2):] # Convert the halves into lists # and sort them l1 = list(left) l1.sort() l2 = list(right) l2.sort() if l1 == l2: print ("Same character in both halves") else: print ("Both halves are different ") in_string = input("Enter String: ") comparehalves(in_string)
Output
Running the above code gives us the following result −
# Run1 Enter String: Tutorials Both halves are different # Run2 Enter String: TutTut Same character in both halves
Advertisements