switch recipe?
Alex Martelli
aleax at aleax.it
Sat Jul 13 03:19:10 EDT 2002
On Saturday 13 July 2002 00:11, Mark McEahern wrote:
...
> In general, this recipe, if it's worthy to be called such, is useful when
> you want to weave together a finite set of values of a given length (n)
> with a different set of values of a different length (m) and for the i-th
> element of n, you want it to be weaved with the len(m) modulo i-th
> element of m.
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
Your approach is more clever (and may have other uses), but this
plain and direct implementation appeals to me. So the function
that uses it might become something like:
def colorize(value, *colors):
return ''.join([ "<%s>%s</%s>" % (color, item, color)
for item, color in weave(value, colors) ])
Alex
More information about the Python-list
mailing list