Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Count all prefixes in given string with greatest frequency using Python
In this tutorial, we will write a Python program that finds all prefixes of a string where one character appears more frequently than another character. This is useful for analyzing character frequency patterns in strings.
Given a string and two characters, we need to find all prefixes where the first character has a higher frequency than the second character, then display the count of such prefixes.
Examples
Example 1
For string "apple" with characters 'p' and 'e' ?
Input: string = "apple", char1 = 'p', char2 = 'e' Output: ap app appl apple Total prefixes matched: 4
Example 2
For string "apple" with characters 'e' and 'p' ?
Input: string = "apple", char1 = 'e', char2 = 'p' Output: Total prefixes matched: 0
Algorithm
The approach involves these steps ?
Initialize a counter to track matching prefixes
Iterate through each position in the string
Extract the prefix from start to current position
Count occurrences of both characters in the prefix
If first character count exceeds second character count, print the prefix and increment counter
Display the total count at the end
Implementation
def count_prefixes_with_greater_frequency(string, char1, char2):
"""
Count prefixes where char1 appears more frequently than char2
"""
count = 0
# Iterate through each position to generate prefixes
for i in range(len(string)):
# Get prefix from start to current position (inclusive)
prefix = string[:i + 1]
# Count occurrences of both characters in current prefix
char1_count = prefix.count(char1)
char2_count = prefix.count(char2)
# Check if first character appears more frequently
if char1_count > char2_count:
print(prefix)
count += 1
print(f"Total prefixes matched: {count}")
return count
# Test with different examples
print("Example 1: string='apple', char1='p', char2='e'")
count_prefixes_with_greater_frequency('apple', 'p', 'e')
print("\nExample 2: string='apple', char1='e', char2='p'")
count_prefixes_with_greater_frequency('apple', 'e', 'p')
print("\nExample 3: string='programming', char1='r', char2='g'")
count_prefixes_with_greater_frequency('programming', 'r', 'g')
Example 1: string='apple', char1='p', char2='e' ap app appl apple Total prefixes matched: 4 Example 2: string='apple', char1='e', char2='p' Total prefixes matched: 0 Example 3: string='programming', char1='r', char2='g' progr progra program programm programmi programmin programming Total prefixes matched: 7
How It Works
The algorithm generates all possible prefixes by slicing the string from index 0 to each position. For each prefix, it uses the count() method to find the frequency of both characters and compares them. Only prefixes where the first character appears more frequently are printed and counted.
Alternative Implementation
Here's a more efficient version that tracks character counts incrementally ?
def count_prefixes_optimized(string, char1, char2):
"""
Optimized version using incremental counting
"""
count = 0
char1_count = 0
char2_count = 0
for i, char in enumerate(string):
# Update character counts incrementally
if char == char1:
char1_count += 1
elif char == char2:
char2_count += 1
# Check if current prefix satisfies condition
if char1_count > char2_count:
prefix = string[:i + 1]
print(prefix)
count += 1
print(f"Total prefixes matched: {count}")
return count
# Test the optimized version
print("Optimized version:")
count_prefixes_optimized('apple', 'p', 'e')
Optimized version: ap app appl apple Total prefixes matched: 4
Conclusion
This program efficiently finds all prefixes where one character appears more frequently than another. The optimized version improves performance by avoiding repeated counting operations for each prefix.
