Haskell -> Python

Duncan Booth duncan.booth at invalid.invalid
Sat Nov 3 17:29:44 CET 2012


Ian Kelly <ian.g.kelly at gmail.com> wrote:

> On Fri, Nov 2, 2012 at 1:19 PM,  <foster63 at gmail.com> wrote:
>> Is there anything anyone could recommend to make it more "Pythonic"
>> or more functional.  It looks clumsy next to the Haskell. 
> 
> def options(heaps):
>     for i, heap in enumerate(heaps):
>         head = heaps[:i]
>         tail = heaps[i+1:]
>         yield from (head + [x] + tail for x in range(heap))
> 
> "yield from" is Python 3.3 syntax.  If you're not using Python 3.3,
> then that line could be replaced by:
> 
>         for x in range(heap):
>             yield head + [x] + tail
> 
> Cheers,
> Ian

An alternative that is closer to foster63's original but still more 
"Pythonic" for some definitions of those words.

def options(heaps):
    if not heaps: return []
    head, *tail = heaps
    for h in range(head):
        yield [h]+tail
    for t in options(tail):
        yield [head]+t

For a more 'functional' version there is also the Python 3.3 variant:

def options(heaps):
    if not heaps: return []
    head, *tail = heaps
    yield from ([h]+tail for h in range(head))
    yield from ([head]+t for t in options(tail))

-- 
Duncan Booth http://kupuguy.blogspot.com


More information about the Python-list mailing list