Comparing objects - is there a maximum object?

Peter Otten __peter__ at web.de
Fri Sep 5 04:07:19 EDT 2003


Chris Brew wrote:

> Thing is, what happens at end of file? I'd like to
> do it by making the streams that are finished
> return some object (call it endmarker) such
> that min(x,endmarker) always returns x. That way,
> when all the streams are returning endmarker, we
> would be done. And I'd like my code to work the same
> no matter what kind of thing the streams are
> returning, so I want endmarker to be a generic
> maximum object.
> 

Why not remove "streams" that have reached the end?
You could do something like

def gen(*seqs):
    seqs = [iter(seq) for seq in seqs]
    done = []
    while True:
        result = []
        for it in seqs:
            try:
                result.append(it.next())
            except StopIteration:
                done.append(it)
        if len(done):
            for d in done:
                seqs.remove(d)
            done = []
        if len(result) == 0:
            break
        yield result

# produce sample data
import random
l1 = range(5)
l2 = range(10)
l3 = range(3, 6)
for l in l1, l2, l3:
    random.shuffle(l)

# demonstration
for i, x in enumerate(gen(l1, l2, l3)):
    print i, x, "-->", min(x)

There may be room for improvement in the gen() function, but the general
idea is not to compare objects made up only for that purpose and when you
already know the outcome.

Peter




More information about the Python-list mailing list