<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def minibatch_by_words(items, size, tuples=True, count_words=len):
 """Create minibatches of a given number of words."""

    if isinstance(size, int):
        size_ = itertools.repeat(size)
    else:
        size_ = size
    items = iter(items)
    while True:
        batch_size = next(size_)
        batch = []
        while batch_size >= 0:
            try:
                if tuples:
                    doc, gold = next(items)
                else:
                    doc = next(items)
            except StopIteration:
                if batch:
                    yield batch
                return
            batch_size -= count_words(doc)
            if tuples:
                batch.append((doc, gold))
            else:
                batch.append(doc)
        if batch:
            yield batch