
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 Any Anagram of a String Is Palindrome in Python
Suppose we have a string s. We have to check whether an anagram of that string is forming a palindrome or not.
So, if the input is like s = "aarcrec", then the output will be True one anagram of this string is "racecar" which is palindrome.
To solve this, we will follow these steps −
- freq := a map to store all characters and their frequencies
- odd_count := 0
- for each f in list of all values of freq, do
- if f is odd, then
- odd_count := odd_count + 1
- if f is odd, then
- if odd_count > 1, then
- return False
- return True
Let us see the following implementation to get better understanding −
Example
from collections import defaultdict def solve(s): freq = defaultdict(int) for char in s: freq[char] += 1 odd_count = 0 for f in freq.values(): if f % 2 == 1: odd_count += 1 if odd_count > 1: return False return True s = "aarcrec" print(solve(s))
Input
"aarcrec"
Output
True
Advertisements