R
Raymond Hettinger
[Steven D'Aprano]:
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
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