N-grams

Paul Rubin no.email at nospam.invalid
Wed Nov 9 21:06:12 EST 2016


This can probably be cleaned up some:

    from itertools import islice
    from collections import deque

    def ngram(n, seq):
        it = iter(seq)
        d = deque(islice(it, n))
        if len(d) != n:
            return
        for s in it:
            yield tuple(d)
            d.popleft()
            d.append(s)
        if len(d) == n:
            yield tuple(d)

    def test():
        xs = range(20)
        for a in ngram(5, xs):
            print a

    test()



More information about the Python-list mailing list