Refactored n_gram function