![]() |
VOOZH | about |
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 = 'geeks are for geeksforgeeks', que_word = "geek"
Output : {'s': 3} Input : test_str = 'geek', que_word = "geek"
Output : {}
Method #1 : Using loop + count() + re.findall()
The combination of the above methods constitutes the brute force method to perform this task. In this, we perform the task of counting using count(), and the character is searched using findall() function.
The original string is : geeksforgeeks is best for geeks. A geek should take interest.
The Characters Frequency is : {'s': 3, ' ': 1}Method #2 : Using Counter() + list comprehension + re.findall()
The combination of the above functions is used to perform the following task. In this, we use Counter() instead of count() to solve this problem. Works with newer versions of Python.
The original string is : geeksforgeeks is best for geeks. A geek should take interest.
The Characters Frequency is : {'s': 3, ' ': 1}Time Complexity: O(n)
Auxiliary Space: O(n)
Method #3 : Using operator.countOf()
The original string is : geeksforgeeks is best for geeks. A geek should take interest.
The Characters Frequency is : {'s': 3, ' ': 1}Time Complexity: O(n)
Auxiliary Space: O(n)
Method 4: Using a loop and dictionary
Example:
The Characters Frequency is: {'s': 3, ' ': 1}Time complexity: O(n), where n is the length of the input string.
Auxiliary space: O(n), as we are storing a dictionary with potentially n/2 keys (if every character in the string follows the queried word) and their corresponding frequencies.
Method #5: Using regex search() and defaultdict()
Step-by-step approach:
Example:
The Characters Frequency is: {'s': 3, ' ': 1}Time Complexity: O(n), where n is the length of the input string.
Auxiliary Space: O(k), where k is the number of distinct characters following the query word.
Method #6: Using itertools.groupby() and Counter()
Step-by-step approach:
The Characters Frequency is: Counter({'s': 3, ' ': 1})Time complexity: O(n), where n is the length of the input string test_str.
Auxiliary space: O(k), where k is the number of unique characters following the query word.