Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - Recursion Functions

Recursive function to count the frequency of characters in a string - Python Program

Example 1 :

def count_char_frequency_recursive(s, char_counts=None): """ Recursively counts the frequency of each character in a string. Args: s (str): The input string. char_counts (dict, optional): A dictionary to store character counts. Used for recursive calls. Defaults to None. Returns: dict: A dictionary where keys are characters and values are their frequencies. """ if char_counts is None: char_counts = {} # Base case: if the string is empty, return the accumulated counts if not s: return char_counts else: # Recursive step: # Get the first character first_char = s[0] # Increment its count in the dictionary char_counts[first_char] = char_counts.get(first_char, 0) + 1 # Recursively call the function with the rest of the string return count_char_frequency_recursive(s[1:], char_counts) # Example Usage: input_string = "programming" frequency_map = count_char_frequency_recursive(input_string) print(f"Input String: '{input_string}'") print(f"Character Frequencies: {frequency_map}") input_string_2 = "hello world" frequency_map_2 = count_char_frequency_recursive(input_string_2) print(f"Input String: '{input_string_2}'") print(f"Character Frequencies: {frequency_map_2}")

Output

 
OUTPUT  :
Input String: 'programming'
Character Frequencies: {'p': 1, 'r': 2, 'o': 1, 'g': 2, 'a': 1, 'm': 2, 'i': 1, 'n': 1}
Input String: 'hello world'
Character Frequencies: {'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}