import math


def filter_unigrams_bigrams(unigram_freqs, bigram_freqs, skip_bigrams=False):
    """
    Filters the unigrams and bigrams by the sqrt of the average frequency.

    :param unigram_freqs: A dictionary mapping the unigrams to their frequency.
    :param bigram_freqs: A dictionary mapping the bigrams to their frequency.
    :param skip_bigrams: Optional. Default: False. Whether or not bigrams should be excluded. Skipping them will result
        in a huge speed increase.
    :return: The filtered unigram and bigram freqs.
    """
    unigram_minimum = round(math.sqrt(sum(unigram_freqs.values()) / len(unigram_freqs)))
    if not skip_bigrams:
        bigram_minimum = round(math.sqrt(sum(bigram_freqs.values()) / len(bigram_freqs)))
        print(f"Bigram length before filter: {len(bigram_freqs)}")
        bigram_freqs = {key: value for key, value in bigram_freqs.items() if value >= bigram_minimum}
        print(f"Bigram length after filter: {len(bigram_freqs)}")
    print(f"Unigram length before filter: {len(unigram_freqs)}")
    unigram_freqs = {key: value for key, value in unigram_freqs.items() if value >= unigram_minimum}
    print(f"Unigram length after filter: {len(unigram_freqs)}")
    return unigram_freqs, bigram_freqs