This code is giving me repeate chars in the table. Fix it def…
- User
This code is giving me repeate chars in the table. Fix it def create_frequency_tables(document, n): # Normalize the document document = document.replace('\n', ' ') characters = list(document)
code# Initialize frequency tables for each n-gram level frequency_tables = [{} for _ in range(n)] length = len(characters) # Count frequencies for each n-gram length from 1 to n for gram_length in range(1, n + 1): for i in range(length - gram_length): n_gram = tuple(characters[i:i + gram_length + 1]) # Include the target character char = n_gram[-1] # The target character (the one we want to predict) prev_chars = n_gram[:-1] # The preceding characters # Initialize if character is not already in the frequency table if char not in frequency_tables[gram_length - 1]: frequency_tables[gram_length - 1][char] = {} # Initialize the context counter if it doesn't exist if prev_chars not in frequency_tables[gram_length - 1][char]: frequency_tables[gram_length - 1][char][prev_chars] = 0 frequency_tables[gram_length - 1][char][prev_chars] += 1 return frequency_tablesFunction to print the frequency tables
def print_table(tables, n): n += 1 for i in range(n): print(f"Table {i + 1} (n(i_{i + 1} | i_{i}, ..., i_1)):") for char, prev_chars_dict in tables[i].items(): for prev_chars, count in prev_chars_dict.items(): print(f" P({char} | {', '.join(prev_chars)}) = {count}")
Example usage
document = "abcd abcd abcd" n = 3 frequency_tables = create_frequency_tables(document, n)
Print the frequency tables
print_table(frequency_tables, n)
- Assistant
- User
Still repeating P(a | ('a',)) = 5 P(a | ('b',)) = 2 P(a | ('c',)) = 3 P(a | ()) = 1 P(b | ('a',)) = 3 P(b | ('c',)) = 1 P(c | ('b',)) = 2 P(c | ('a',)) = 2 P(c | ('c',)) = 1
- Assistant
- User
only edit create_frequency_tables to fix the problem
- Assistant
Certainly! Let's focus on fixing the function to ensure that we accurately count the n-grams without repeating counts for contexts.