
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
Program to find length of longest anagram subsequence in Python
In Python, a string is immutable data structure in which sequence of characters are enclosed in double("") or single quotes(''). In some cases, we need to find the length of the longest subsequence of characters that can be rearranged to form a palindrome. This type of subsequence is referred to as a palindromic anagram subsequence. To solve this, we need to count how many characters appear an even number of times and at most one character can appear an odd number of times.
An anagram is a word or phrase formed by rearranging the letters of another word or phrase by using all the original letters exactly once. In other words, two strings are said to be anagrams of each other if they contain the same characters in the same quantity but possibly in a different order.
Using collections.Counter Class
The Counter class from the collections module in Python is used for counting how many times each character appears in a string. To build the longest palindrome using the characters from the string, we have to use all even-count characters and if available, one character with an odd count placed in the middle.
Example-1
Following is the example which shows how to count each character using the Counter class to determine the length of the longest subsequence that can be rearranged as a palindrome -
from collections import Counter def longest_anagram_subsequence_length(s): freq = Counter(s) length = 0 odd_found = False for count in freq.values(): if count % 2 == 0: length += count else: length += count - 1 odd_found = True if odd_found: length += 1 return length # Sample input string s = "abccccdd" print("Length of longest anagram subsequence:", longest_anagram_subsequence_length(s))
Here is the output of the above example -
Length of longest anagram subsequence: 7
Example-2
Below is another example where we calculate the length of the longest palindromic anagram subsequence -
from collections import Counter def longest_palindrome_length(s): count = Counter(s) result = 0 for freq in count.values(): result += (freq // 2) * 2 if result % 2 == 0 and freq % 2 == 1: result += 1 return result # Sample input string s = "aabbc" print("Longest anagram subsequence length:", longest_palindrome_length(s))
Below is the output of the above example -
Longest anagram subsequence length: 5