Classical FP problem in python : Hamming problem
Steven Bethard
steven.bethard at gmail.com
Tue Jan 25 13:52:15 EST 2005
Nick Craig-Wood wrote:
> Steven Bethard <steven.bethard at gmail.com> wrote:
>
>> Nick Craig-Wood wrote:
>>
>>>Thinking about this some more leads me to believe a general purpose
>>>imerge taking any number of arguments will look neater, eg
>>>
>>>def imerge(*generators):
>>> values = [ g.next() for g in generators ]
>>> while True:
>>> x = min(values)
>>> yield x
>>> for i in range(len(values)):
>>> if values[i] == x:
>>> values[i] = generators[i].next()
>>>
>>
>> This kinda looks like it dies after the first generator is exhausted,
>> but I'm not certain.
>
>
> Yes it will stop iterating then (rather like zip() on lists of unequal
> size). Not sure what the specification should be! It works for the
> hamming problem though.
Actually, it stops iterating on lists of equal size too:
py> def imerge(*iterators):
... iterators = [iter(i) for i in iterators]
... values = [i.next() for i in iterators]
... while True:
... x = min(values)
... yield x
... for i, val in enumerate(values):
... if val == x:
... values[i] = iterators[i].next()
...
py> list(imerge([1, 4, 7], [2, 5, 8], [3, 6, 9]))
[1, 2, 3, 4, 5, 6, 7]
Note that 8 and 9 are not in the list.
Steve
More information about the Python-list
mailing list