which one do you prefer? python with C# or java?

Alexander Blinne news at blinne.net
Mon Jun 11 13:23:57 EDT 2012


On 10.06.2012 23:27, Paul Rubin wrote:
> Here is an exercise from the book that you might like to try in Python:
> 
>   http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-24.html#%_idx_3894
> 
> It's not easy ;-)

I liked this exercize. At first I wrote my own merger.

> def merge(*iterables):
>     iterables = list(iterables)
>     current = [i.next() for i in iterables]
>     last = None
>     while True:
>         m = min(current)
>         while last == m:
>             p = current.index(m)
>             try:
>                 current[p] = iterables[p].next()
>             except StopIteration:
>                 del current[p]
>                 del iterables[p]
>             if len(current) == 0:
>                 raise StopIteration
>             m = min(current)    
>         yield m
>         last = m

But then I realised the vast library of python already contained (a
faster) one (propably based upon
<http://code.activestate.com/recipes/491285-iterator-merge/>), which
just needed to be enhanced a little bit to allow duplicate items to be
removed:

> import heapq
> 
> def skipdups(m):
>     l = k = m.next()
>     yield k
>     while True:
>         while l == k:
>             k = m.next()
>         yield k
>         l = k
> 
> def gen_s():
>   s = [1]
>   m = skipdups(heapq.merge(*[(lambda j: (k*j for k in s))(n) for n in [2,3,5]]))
>   yield s[0]
>   while True:
>       k = m.next()
>       s.append(k)
>       yield k

Now gen_s() generates the wanted sequence.

Greetings



More information about the Python-list mailing list