Coolest Python recipe of all time

  • Thread starter Raymond Hettinger
  • Start date
R

Raymond Hettinger

[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
 
S

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.

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?
 
I

Ian Kelly

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.
 
T

Trent Nelson

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])
 
R

Raymond Hettinger

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 thelazy 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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,780
Messages
2,569,608
Members
45,252
Latest member
MeredithPl

Latest Threads

Top