import random


def reservoir_sample(stream, size):
    """
    maintains a random sample from a stream.
    Args:
        stream: iterable item
        size: size of the sample you want
    """
    reservoir = []    
    for i, x in enumerate(stream, start=1):
        if i <= size:
            reservoir.append(x)
        elif random.random() < (1 / i):
            reservoir[random.randint(0, size-1)] = x
    return reservoir