
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
In Python, a string is one of the data structures that is a sequence of characters enclosed within single quotes '' or double quotes "". It is immutable, i.e., once a string is created, it cannot be changed.
When we want to check if both halves of the string have the same set of characters in Python, we can follow the steps below -
- First, based on the length of the string, we have to split the string into two halves.
- Next, convert each half into a set of characters using set() function.
- Finally, compare the two sets using the equality operator ==.
Using set() function
set() is a built-in function in Python that is an unordered collection of unique elements. Sets are mutable, but the elements contained in a set must be immutable. This function takes a string, list, tuple, etc, as input.
Example
In this example, we will check for the same set of characters in both halves of a string with the help of the set() function by passing the string as the input -
def check_same_characters_in_halves(s): length = len(s) # If length is odd, ignore the middle character mid = length // 2 first_half = set(s[:mid]) second_half = set(s[-mid:]) return first_half == second_half # Test cases print(check_same_characters_in_halves("abcabc")) # True print(check_same_characters_in_halves("aabbcc")) # True print(check_same_characters_in_halves("abcdab")) # False print(check_same_characters_in_halves("abcdeabc")) # False
Following is the output of the above example -
True False False False
Using collections.Counter class
collections.Counter is a class in Python's collections module, which is used to count the frequency of elements in an iterable. It returns a dictionary-like object where elements are stored as dictionary keys and their counts as dictionary values.
Example
In this example, we will check for the same characters and their frequencies in both halves of a string with the help of collections.Counter class by passing string slices as input -
from collections import Counter def check_same_character_frequencies(s): length = len(s) # If length is odd, ignore the middle character mid = length // 2 first_half = s[:mid] second_half = s[-mid:] return Counter(first_half) == Counter(second_half) # Test cases print(check_same_character_frequencies("tutorialspoint")) # False print(check_same_character_frequencies("TutTut")) # True print(check_same_character_frequencies("Learning")) # False print(check_same_character_frequencies("python")) # False
Below is the output of the above example -
False True False False