How to generate all trigrams (3-character sequences) from a given word in Python

1 Answer

0 votes
"""
    -------------------------------------------------------------------------
    What is a trigram?
    -------------------------------------------------------------------------
    A trigram is a sequence of exactly three consecutive characters taken
    from a word. To generate all trigrams, we slide a window of length 3
    across the string. Each step produces a new 3‑character slice.

    Example:
        Word: "magic"
        Trigrams: ["mag", "agi", "gic"]

    Trigrams are useful in text processing, search algorithms,
    and language modeling because they capture small structural patterns
    inside words.
"""

def make_trigrams(word: str) -> list[str]:
    """
    Return all trigrams (3‑character sequences) from the given word.

    Steps:
      - If the word is shorter than 3 characters, return an empty list.
      - Otherwise, slide a window of size 3 across the word.
      - Use slicing to extract each 3‑character sequence.

    The algorithm runs in O(n) time and uses O(n) space.
    """
    if len(word) < 3:
        return []

    count = len(word) - 2

    return [word[i:i+3] for i in range(count)]


def main():
    """
    Main program:
      - Read a word from the user.
      - Generate trigrams.
      - Print each trigram.
    """
    word = input("Enter a word: ").strip()
    trigrams = make_trigrams(word)

    print("\nTrigrams:")
    for t in trigrams:
        print(t)


if __name__ == "__main__":
    main()



"""
run:

Enter a word: computer

Trigrams:
com
omp
mpu
put
ute
ter

"""

 



answered Sep 9 by avibootz
...