From 83366244b23a1af286c005d8c18954002f2b525c Mon Sep 17 00:00:00 2001 From: Baharan Meghdadi Date: Wed, 21 Aug 2024 10:03:26 -0400 Subject: [PATCH] adjusted code.py for readability --- code.py | 49 ++++++++++++++++++++++++++++++++++++------------- 1 file changed, 36 insertions(+), 13 deletions(-) diff --git a/code.py b/code.py index 7bfc82b..418fc4f 100644 --- a/code.py +++ b/code.py @@ -1,16 +1,39 @@ -def function1(a): - b = dict() - for c in a: - if c not in b: - b[c] = 1 +def calculate_character_frequency(input_string): + """ + Computes the frequency of each character in the input string. + + Parameters: + input_string (str): The string for which character frequency is calculated. + + Returns: + dict: A dictionary where keys are characters and values are their corresponding counts in the input string. + """ + frequency_dict = dict() + for char in input_string: + if char not in frequency_dict: + frequency_dict[char] = 1 # Initialize the count if the character is not in the dictionary. else: - b[c] += 1 - return b + frequency_dict[char] += 1 # Increment the count if the character is already in the dictionary. + return frequency_dict + +def normalize_character_frequencies(frequency_dict): + """ + Prints the normalized frequency of each character based on their counts from the input dictionary. + + Parameters: + frequency_dict (dict): A dictionary where keys are characters and values are their corresponding counts. -def function2(a): - print('freqs') - total = float(sum([a[b] for b in a.keys()])) - for b in a.keys(): - print(b + ':' + str(a[b]/total)) + Returns: + None: This function prints the frequencies directly to the console. + """ + print('Frequencies:') + total_count = sum(frequency_dict.values()) # Calculate the total count of all characters. + + for char, count in frequency_dict.items(): + frequency = count / total_count # Calculate the frequency of each character. + print(f'{char}: {frequency:.4f}') # Print each character and its frequency, formatted to 4 decimal places. -function2(function1('ATCTGACGCGCGCCGC')) +# Example usage: calculate fraction of nucleobases in a given string. +input_string = 'ATCTGACGCGCGCCGC' +frequency_dict = calculate_character_frequency(input_string) +normalize_character_frequencies(frequency_dict) \ No newline at end of file