switch recipe?

Mark McEahern marklists at mceahern.com
Mon Jul 15 15:31:21 EDT 2002


[Alex Martelli]
> Right.  So what about a direct implementation of what you just said?
>
> def weave(setn, setm):
>     n = len(setn)
>     m = len(setm)
>     if not n or not m:
>         raise ValueError, "Weaved sets cannot be empty"
>     yield setn[0], setm[0]
>     i = 1
>     while i%n or i%m:
>         yield setn[i%n], setm[i%m]
>         i += 1

I like this.  The 'or' in the while statment means this will loop until
lcd(n, m)--easily fixed.  I modified this slightly:

def weave(setn, setm):
    """Return a generator that iterates over setn and setm until setn is
    exhausted.  If setn is larger than setm, cycle over setm.
    """
    m = len(setm)
    if not setn or not setm:
        raise ValueError, "Weaved sets cannot be empty"
    for i in range(len(setn)):
        yield setn[i], setm[i%m]

This means you have to specify the alternator/cycler second--it doesn't
treat the two sets as interchangeable.  Slightly less general than the
direction your solution points.

// m

-






More information about the Python-list mailing list