Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #4488 > unrolled thread

Coolest Python recipe of all time

Started byRaymond Hettinger <python@rcn.com>
First post2011-05-02 10:33 -0700
Last post2011-05-09 14:10 -0700
Articles 6 on this page of 26 — 10 participants

Back to article view | Back to comp.lang.python


Contents

  Coolest Python recipe of all time Raymond Hettinger <python@rcn.com> - 2011-05-02 10:33 -0700
    Re: Coolest Python recipe of all time David Monaghan <monaghand.david@gmail.com> - 2011-05-02 21:48 +0100
      Re: Coolest Python recipe of all time Ian Kelly <ian.g.kelly@gmail.com> - 2011-05-02 14:58 -0600
        Re: Coolest Python recipe of all time David Monaghan <monaghand.david@gmail.com> - 2011-05-02 22:45 +0100
          Re: Coolest Python recipe of all time Stefan Behnel <stefan_ml@behnel.de> - 2011-05-03 07:04 +0200
            Re: Coolest Python recipe of all time Raymond Hettinger <python@rcn.com> - 2011-05-03 09:43 -0700
              Re: Coolest Python recipe of all time Chris Angelico <rosuav@gmail.com> - 2011-05-04 07:54 +1000
              Re: Coolest Python recipe of all time Ian Kelly <ian.g.kelly@gmail.com> - 2011-05-03 16:10 -0600
          Re: Coolest Python recipe of all time Ian Kelly <ian.g.kelly@gmail.com> - 2011-05-02 23:17 -0600
          Re: Coolest Python recipe of all time Terry Reedy <tjreedy@udel.edu> - 2011-05-03 02:00 -0400
            Re: Coolest Python recipe of all time Gregory Ewing <greg.ewing@canterbury.ac.nz> - 2011-05-03 18:29 +1200
              Re: Coolest Python recipe of all time Terry Reedy <tjreedy@udel.edu> - 2011-05-03 11:49 -0400
              Re: Coolest Python recipe of all time Raymond Hettinger <python@rcn.com> - 2011-05-03 09:32 -0700
              Re: Coolest Python recipe of all time geremy condra <debatem1@gmail.com> - 2011-05-03 09:51 -0700
          Re: Coolest Python recipe of all time Stefan Behnel <stefan_ml@behnel.de> - 2011-05-03 08:23 +0200
            Re: Coolest Python recipe of all time Raymond Hettinger <python@rcn.com> - 2011-05-03 15:19 -0700
    Re: Coolest Python recipe of all time Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2011-05-06 16:59 +0000
      Re: Coolest Python recipe of all time geremy condra <debatem1@gmail.com> - 2011-05-06 10:43 -0700
      Re: Coolest Python recipe of all time Ian Kelly <ian.g.kelly@gmail.com> - 2011-05-06 12:36 -0600
        Re: Coolest Python recipe of all time Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2011-05-07 08:29 +0000
          Re: Coolest Python recipe of all time Ian Kelly <ian.g.kelly@gmail.com> - 2011-05-07 08:54 -0600
          Re: Coolest Python recipe of all time Raymond Hettinger <python@rcn.com> - 2011-05-07 14:02 -0700
      Re: Coolest Python recipe of all time Ian Kelly <ian.g.kelly@gmail.com> - 2011-05-06 13:38 -0600
      Re: Coolest Python recipe of all time Raymond Hettinger <python@rcn.com> - 2011-05-06 12:58 -0700
    RE: Coolest Python recipe of all time Trent Nelson <trent@snakebite.org> - 2011-05-09 02:31 -0700
      Re: Coolest Python recipe of all time Raymond Hettinger <python@rcn.com> - 2011-05-09 14:10 -0700

Page 2 of 2 — ← Prev page 1 [2]


#4910

FromIan Kelly <ian.g.kelly@gmail.com>
Date2011-05-07 08:54 -0600
Message-ID<mailman.1292.1304780095.9059.python-list@python.org>
In reply to#4891
On Sat, May 7, 2011 at 2:29 AM, Steven D'Aprano
<steve+comp.lang.python@pearwood.info> wrote:
>> This isn't really amb; as you said it's just a brute-force solver with
>> some weird syntax.  The whole point of amb is to enable
>> non-deterministic programming, such as this:
> [...]
>> The amb engine would conceptually execute this function for every
>> possible combination of a, b, and c,
>
> Which pretty much is the definition of "brute-force solver", no?

The "execute the function for every possible combination" part, yes.
The "non-deterministic programming" part, no.

[toc] | [prev] | [next] | [standalone]


#4919

FromRaymond Hettinger <python@rcn.com>
Date2011-05-07 14:02 -0700
Message-ID<dc341f4c-6de6-43ca-9258-30ec71d58dd3@h12g2000pro.googlegroups.com>
In reply to#4891
On May 7, 1:29 am, Steven D'Aprano <steve
+comp.lang.pyt...@pearwood.info> wrote:
> On Fri, 06 May 2011 12:36:09 -0600, Ian Kelly wrote:
> > The amb engine would conceptually execute this function for every
> > possible combination of a, b, and c,
>
> Which pretty much is the definition of "brute-force solver", no?

FWIW, here's one of my favorite brute-force solvers:

   http://code.activestate.com/recipes/576615-alphametics-solver/


Raymond

-------
follow my recipes and tips on twitter:  @raymondh

[toc] | [prev] | [next] | [standalone]


#4853

FromIan Kelly <ian.g.kelly@gmail.com>
Date2011-05-06 13:38 -0600
Message-ID<mailman.1261.1304710722.9059.python-list@python.org>
In reply to#4840
On Fri, May 6, 2011 at 12:36 PM, Ian Kelly <ian.g.kelly@gmail.com> wrote:
> This is typically implemented using continuations, and I'm not sure
> whether a true amb could actually be achieved in Python without adding
> continuations or flow-control macros to the language.

I stand corrected.  After poking around a bit more I found this recipe
that is designed for unit-testing but implements amb beautifully.

http://lackingrhoticity.blogspot.com/2009/08/how-to-do-model-checking-of-python-code.html

My code from the previous post using this recipe:

def find_values(chooser):
    def amb(*choices):
        return chooser.choose(choices)
    def require(x):
        if not x:
            amb()
    a = amb(1, 3, 5)
    b = amb(2, 4, 8)
    require(a + b > 5)
    require(is_prime(a * b + 1))
    c = amb(a, b, None)
    require(c is None or c >= 5)
    return a, b, c

check(find_values)

The one downside is that the check function (again, designed for
unit-testing) does not provide any way to retrieve the returned
values, but that is easily solved by rewriting as a generator.

Cheers,
Ian

[toc] | [prev] | [next] | [standalone]


#4861

FromRaymond Hettinger <python@rcn.com>
Date2011-05-06 12:58 -0700
Message-ID<31819e29-a02f-4721-bb75-5decbd0056ae@i39g2000prd.googlegroups.com>
In reply to#4840
[Steven D'Aprano]:
> As written, amb is just a brute-force solver using more magic than is
> good for any code, but it's fun to play with.

With a small change in API, much of the magic isn't needed.

from itertools import product

def amb(func, *argument_ranges):
    for args in product(*argument_ranges):
        if func(*args):
            print(args)

amb(lambda a,b,c,d: 5*a+10*b+20*c+50*d == 45,
    range(3, 21),   # number of 5 cent coins
    range(11),      # number of 10 cent coins
    range(6),       # number of 20 cent coins
    range(3),       # number of 50 cent coins
)

def test(a, b, c, d):
    s = "The %s brown %s jumped over the %s %s." % (a, b, c, d)
    num_vowels = sum(s.count(c) for c in 'aeiou')
    return num_vowels in (12, 18, 19)

amb(test,
    ['quick', 'slow', 'hungry', 'wise-old'],
    ['fox', 'hare', 'turtle', 'kangaroo'],
    ['lazy', 'stupid', 'sleepy', 'confused'],
    ['dog', 'aardvark', 'sloth', 'wombat'],
)

amb(lambda x, y, z: x*x + y*y == z*z,
    range(1, 11),
    range(1, 11),
    range(1, 11),
)


Raymond

------------
follow my recipes and tips on twitter: @raymondh

[toc] | [prev] | [next] | [standalone]


#4986

FromTrent Nelson <trent@snakebite.org>
Date2011-05-09 02:31 -0700
Message-ID<mailman.1327.1304933610.9059.python-list@python.org>
In reply to#4488
> What are your favorites?

I think I've posted this before, but I love my 3-lines-if-you-ignore-the-scaffolding language translator.  Not because it's clever code -- quite the opposite, the code is dead simple -- but because it encompasses one of the things I love about Python the most: it gets shit done.

    In [1]: from translate import *

    In [2]: translate('French', 'The quick brown fox jumped over the lazy dog.')
    Le renard brun rapide a sauté par-dessus le chien paresseux.

    In [3]: translate('German', 'The quick brown fox jumped over the lazy dog.')
    Der schnelle braune Fuchs sprang über den faulen Hund.

    In [4]: translate('Spanish', 'The quick brown fox jumped over the lazy dog.')
    El zorro marrón rápido saltó sobre el perro perezoso.

translate.py:

    import sys
    from urllib import urlopen, urlencode
    from BeautifulSoup import BeautifulSoup

    url = 'http://babelfish.altavista.com/tr'
    languages = {
        'French'    : 'en_fr',
        'German'    : 'en_de',
        'Italian'   : 'en_it',
        'Spanish'   : 'en_es',
        'Russian'   : 'en_ru',
        'Portuguese': 'en_pt',
        'Dutch'     : 'en_nl',
        'Japanese'  : 'en_ja',
    }

    def translate(lang, text):
        kwds = { 'trtext' : text, 'lp' : languages[lang]}
        soup = BeautifulSoup(urlopen(url, urlencode(kwds)))
        print soup.find('div', style='padding:10px;').string

    if __name__ == '__main__':
        translate(sys.argv[1], sys.argv[2])

[toc] | [prev] | [next] | [standalone]


#5031

FromRaymond Hettinger <python@rcn.com>
Date2011-05-09 14:10 -0700
Message-ID<55c0b493-7d4e-42c2-a411-537c68a058b3@b7g2000prg.googlegroups.com>
In reply to#4986
On May 9, 2:31 am, Trent Nelson <tr...@snakebite.org> wrote:
> > What are your favorites?
>
> I think I've posted this before, but I love my 3-lines-if-you-ignore-the-scaffolding language translator.  Not because it's clever code -- quite the opposite, the code is dead simple -- but because it encompasses one of the things I love about Python the most: it gets shit done.
>
>     In [1]: from translate import *
>
>     In [2]: translate('French', 'The quick brown fox jumped over the lazy dog.')
>     Le renard brun rapide a sauté par-dessus le chien paresseux.
>
>     In [3]: translate('German', 'The quick brown fox jumped over the lazy dog.')
>     Der schnelle braune Fuchs sprang über den faulen Hund.
>
>     In [4]: translate('Spanish', 'The quick brown fox jumped over the lazy dog.')
>     El zorro marrón rápido saltó sobre el perro perezoso.
>
> translate.py:
>
>     import sys
>     from urllib import urlopen, urlencode
>     from BeautifulSoup import BeautifulSoup
>
>     url = 'http://babelfish.altavista.com/tr'
>     languages = {
>         'French'    : 'en_fr',
>         'German'    : 'en_de',
>         'Italian'   : 'en_it',
>         'Spanish'   : 'en_es',
>         'Russian'   : 'en_ru',
>         'Portuguese': 'en_pt',
>         'Dutch'     : 'en_nl',
>         'Japanese'  : 'en_ja',
>     }
>
>     def translate(lang, text):
>         kwds = { 'trtext' : text, 'lp' : languages[lang]}
>         soup = BeautifulSoup(urlopen(url, urlencode(kwds)))
>         print soup.find('div', style='padding:10px;').string
>
>     if __name__ == '__main__':
>         translate(sys.argv[1], sys.argv[2])

That completely rocks!  Thanks for the recipe.


Raymond

----------
follow my recipes and tips on twitter: @raymondh

[toc] | [prev] | [standalone]


Page 2 of 2 — ← Prev page 1 [2]

Back to top | Article view | comp.lang.python


csiph-web