
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
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
Advertisements