Open In App

Python – Odd Frequency Characters

Last Updated : 25 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with Python strings, we can have a problem in which we need to extract all the string characters which have odd number of occurrences. This problem can have applications in domains such as data domain and day-day programming. Let’s discuss certain ways in which this task can be performed.

Illustrations:

Input : test_str = 'geekforgeeks' 
Output : ['r', 'o', 'f', 's'] 
Input : test_str = 'g' 
Output : ['g']

Method #1 : Using defaultdict() + list comprehension + loop 

The combination of the above functions can be used to solve this problem. In this, we initialize the defaultdict() with integer and then perform frequency count. List comprehension is used to extract all the odd frequencies.

Python3




# Python3 code to demonstrate working of
# Odd Frequency Characters
# Using list comprehension + defaultdict()
from collections import defaultdict
 
# helper_function
def hlper_fnc(test_str):
    cntr = defaultdict(int)
    for ele in test_str:
        cntr[ele] += 1
    return [val for val, chr in cntr.items() if chr % 2 != 0]
 
# initializing string
test_str = 'geekforgeeks is best for geeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# Odd Frequency Characters
# Using list comprehension + defaultdict()
res = hlper_fnc(test_str)
 
# printing result
print("The Odd Frequency Characters are :" + str(res))


Output : 

The original string is : geekforgeeks is best for geeks
The Odd Frequency Characters are : ['k', 'i', 't', 'g', 'e', 'b']

Method #2 : Using list comprehension + Counter() 

The combination of the above functionalities can be used to solve this problem. In this, we use Counter() to count the frequency. 

Python3




# Python3 code to demonstrate working of
# Odd Frequency Characters
# Using list comprehension + Counter()
 
from collections import Counter
 
# initializing string
test_str = 'geekforgeeks is best for geeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# Odd Frequency Characters
# Using list comprehension + Counter()
res = [chr for chr, count in Counter(test_str).items() if count & 1]
 
# printing result
print("The Odd Frequency Characters are : " + str(res))


Output : 

The original string is : geekforgeeks is best for geeks
The Odd Frequency Characters are : ['k', 'i', 't', 'g', 'e', 'b']

Method #3 : Using count() method.

Using set() we will remove duplicates in a string, after that, we find the frequency of each character in the string using the count() method. If the frequency is odd then append it to the output list.

Python3




# Python3 code to demonstrate working of
# Odd Frequency Characters
 
 
# initializing string
test_str = 'geekforgeeks is best for geeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# Odd Frequency Characters
x=set(test_str)
res=[]
for i in x:
    if(test_str.count(i)%2!=0):
        res.append(i)
# printing result
print("The Odd Frequency Characters are : " + str(res))


Output

The original string is : geekforgeeks is best for geeks
The Odd Frequency Characters are : ['k', 'e', 'i', 't', 'g', 'b']

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #4 : Using operator.countOf() method.

Python3




# Python3 code to demonstrate working of
# Odd Frequency Characters
import operator as op
 
# initializing string
test_str = 'geekforgeeks is best for geeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# Odd Frequency Characters
x=set(test_str)
res=[]
for i in x:
    if(op.countOf(test_str,i)%2!=0):
        res.append(i)
# printing result
print("The Odd Frequency Characters are : " + str(res))


Output

The original string is : geekforgeeks is best for geeks
The Odd Frequency Characters are : ['i', 'b', 'e', 'k', 'g', 't']

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #5: Using a dictionary and a loop

  • The function takes a string test_str as input.
  • An empty dictionary char_counts is created to hold the counts of each character in the string.
  • The function loops through each character char in the string test_str.
  • For each character, the function uses the get method to safely retrieve the current count for that character in the dictionary. If the character has not been encountered before, get will return a default value of 0. The count is then incremented by 1.
  • After all characters have been counted, the function creates a new list containing only the characters whose counts are odd. This is done using a list comprehension that iterates over the items() of the char_counts dictionary. For each character char and count count pair, the function checks if count % 2 != 0 (i.e., the count is odd). If so, the character is included in the list.
  • The list of odd-frequency characters is returned.

Python3




def odd_freq_chars(test_str):
    # Create an empty dictionary to hold character counts
    char_counts = {}
 
    # Loop through each character in the input string
    for char in test_str:
        # Increment the count for this character in the dictionary
        # using the get() method to safely handle uninitialized keys
        char_counts[char] = char_counts.get(char, 0) + 1
 
    # Create a list of characters whose counts are odd
    return [char for char, count in char_counts.items() if count % 2 != 0]
 
 
# Test the function with sample input
test_str = 'geekforgeeks is best for geeks'
print("The original string is : " + str(test_str))
res = odd_freq_chars(test_str)
print("The Odd Frequency Characters are :" + str(res))


Output

The original string is : geekforgeeks is best for geeks
The Odd Frequency Characters are :['g', 'e', 'k', 'i', 'b', 't']

Time complexity: O(n), where n is the length of the input string, 
Auxiliary space: O(k), where k is the number of unique characters in the string. The space complexity is due to the dictionary that is created to store the character counts.

Method 6: Using the collections.defaultdict and collections.Counter classes:

Python3




# Python3 code to demonstrate working of
# Odd Frequency Characters
 
from collections import defaultdict, Counter
 
# initializing string
test_str = 'geekforgeeks is best for geeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# Odd Frequency Characters using defaultdict
char_count = defaultdict(int)
for c in test_str:
    char_count += 1
 
odd_freq_chars = % 2 != 0]
 
# printing result
print("The Odd Frequency Characters are : " + str(odd_freq_chars))
 
# Odd Frequency Characters using Counter
char_count = Counter(test_str)
 
odd_freq_chars = % 2 != 0]
 
# printing result
print("The Odd Frequency Characters are : " + str(odd_freq_chars))


Output

The original string is : geekforgeeks is best for geeks
The Odd Frequency Characters are : ['g', 'e', 'k', 'i', 'b', 't']
The Odd Frequency Characters are : ['g', 'e', 'k', 'i', 'b', 't']

Time complexity: O(n) since we iterate through each character of the input string once.
Auxiliary Space O(k), where k is the number of distinct characters in the input string.



Similar Reads

Maximum length prefix such that frequency of each character is atmost number of characters with minimum frequency
Given a string S, the task is to find the prefix of string S with the maximum possible length such that frequency of each character in the prefix is at most the number of characters in S with minimum frequency. Examples: Input: S = 'aabcdaab' Output: aabcd Explanation: Frequency of characters in the given string - {a: 4, b: 2, c: 1, d: 1} Minimum f
8 min read
Python | Consecutive characters frequency
Sometimes, while working with Python, we can have a problem in which we need to compute the frequency of consecutive characters till the character changes. This can have applications in many domains. Let us discuss certain ways in which this task can be performed in Python. Python Program to Count Consecutive Characters FrequencyUsing list comprehe
5 min read
Python - Successive Characters Frequency
Sometimes, while working with Python strings, we can have a problem in which we need to find the frequency of next character of a particular word in string. This is quite unique problem and has the potential for application in day-day programming and web development. Let's discuss certain ways in which this task can be performed. Input : test_str =
6 min read
Python - Specific Characters Frequency in String List
Given a String list, extract frequency of specific characters in the whole strings list. Input : test_list = ["geeksforgeeks is best for geeks"], chr_list = ['e', 'b', 'g', 'f'] Output : {'g': 3, 'e': 7, 'b': 1, 'f' : 2} Explanation : Frequency of certain characters extracted. Input : test_list = ["geeksforgeeks"], chr_list = ['e', 'g'] Output : {'
5 min read
Check if a substring exists having only 2 distinct characters with frequency of one as twice the others
Given a string str[] of N lower case English alphabets, the task is to check if there exists a substring of the given string such that the substring is composed of only two characters and the frequency of 1st character = 2 * frequency of 2nd character. Example: Input: str[] = "aaaabbc"Output: YesExplanation: The substring str[0... 5] = "aaaabb" of
6 min read
Print Even and Odd Index Characters of a String - Python
Given a string, our task is to print odd and even characters of a string in Python. Example Input: GeeksforgeeksOutput: Gesoges ekfrekUsing Brute-Force Approach to get even and odd index charactersFirst, create two separate lists for even and odd characters. Iterate through the given string and then check if the character index is even or odd. Even
2 min read
Python | Convert list of strings and characters to list of characters
Sometimes we come forward to the problem in which we receive a list that consists of strings and characters mixed and the task we need to perform is converting that mixed list to a list consisting entirely of characters. Let's discuss certain ways in which this is achieved. Method #1 : Using List comprehension In this method, we just consider each
6 min read
Python program to print k characters then skip k characters in a string
Given a String, extract K characters alternatively. Input : test_str = 'geeksgeeksisbestforgeeks', K = 4 Output : geekksisforg Explanation : Every 4th alternate range is sliced. Input : test_str = 'geeksgeeksisbest', K = 4 Output : geekksis Explanation : Every 4th alternate range is sliced. Method #1 : Using loop + slicing In this, we perform task
5 min read
Find frequency of each word in a string in Python
Write a python code to find the frequency of each word in a given string. Examples: Input : str[] = "Apple Mango Orange Mango Guava Guava Mango" Output : frequency of Apple is : 1 frequency of Mango is : 3 frequency of Orange is : 1 frequency of Guava is : 2 Input : str = "Train Bus Bus Train Taxi Aeroplane Taxi Bus" Output : frequency of Train is
7 min read
Python | Count all prefixes in given string with greatest frequency
Given a string, print and count all prefixes in which first alphabet has greater frequency than second alphabet.Take two alphabets from the user and compare them. The prefixes in which the alphabet given first has greater frequency than the second alphabet, such prefixes are printed, else the result will be 0. Examples : Input : string1 = "geek", a
4 min read
Practice Tags :
three90RightbarBannerImg