[Baypiggies] a python puzzle

Thomas Belote tbelote at tombelote.com
Wed Apr 14 18:20:17 CEST 2010


Here is my solution, change how next works so it is compatible with your while conditions:

import itertools

def fnext(next):
    try:
        return next()
    except:
        return False, []

def as_pairs(xs, ys, grouper=lambda _: _):
    # assume xs and ys are sorted.    
    xgrouper = itertools.groupby(xs, grouper)
    ygrouper = itertools.groupby(ys, grouper)
    x, xgroup = fnext(xgrouper.next)
    y, ygroup = fnext(ygrouper.next)
    while x or y:
        if x == y:
            yield list(xgroup), list(ygroup)
            try:
                x, xgroup = fnext(xgrouper.next)
                y, ygroup = fnext(ygrouper.next)
            except:
                traceback.print_exc()
        elif not y or x < y:
            yield list(xgroup), None
            x, xgroup = fnext(xgrouper.next)
        elif not x or x > y:
            yield (None, list(ygroup))
            y, ygroup = fnext(ygrouper.next)
        print repr(x) + " or " + repr(y)




aordered = [1, 1, 2, 4, 6, 8, 9]
bordered = [1, 3, 4, 5, 6, 7, 8]
for a, b in as_pairs(aordered, bordered):
    a, b

On Apr 14, 2010, at 8:20 AM, Brent Pedersen wrote:

> hi, in trying to write a func that does a kind of merging of 2 sorted lists,
> i've come up with a fairly simple implementation that "almost works":
> http://gist.github.com/365485
> 
> but it hits StopIteration before returning the last value ([9], None)
> i can wrap the whole thing in a bunch more if statements, i've tried
> heapq.merge, but cant find a nice solution.
> 
> any ideas? i think it's an interesting problem.
> -brent
> _______________________________________________
> Baypiggies mailing list
> Baypiggies at python.org
> To change your subscription options or unsubscribe:
> http://mail.python.org/mailman/listinfo/baypiggies



More information about the Baypiggies mailing list