number generator
Anton Vredegoor
anton.vredegoor at gmail.com
Wed Mar 14 06:08:42 EDT 2007
Raymond Hettinger wrote:
> Since people are posting their solutions now (originally only hints
> were provided for the homework problem), here's mine:
Homework problem? Do you have some information from the OP that I can't
find in this thread? Anyway, I consider the 'homework' idea and the
associated self concept that turns people into -for example-
backstabbing computer scientists who never release their code as the
root of all evil in the educational system. Why should I uphold a moral
code that I don't agree with? To me people posting homework problems are
like refugees which I will help if I can.
> def genpool(n, m):
> if n == 1:
> yield [m]
> else:
> for i in xrange(1, m):
> for rest in genpool(n-1, m-i):
> yield rest + [i]
>
> import random
> print random.choice(list(genpool(n=4, m=20)))
OK back to the *computer* code. Great function! And it's ideally suited
for memoization too. Too bad this memoizor doesn't accept keyword
arguments, but for the rest it works fine and greatly speeds it up.
import random
def memoize(fn):
cache = {}
def proxy(*args):
try: return cache[args]
except KeyError: return cache.setdefault(args, fn(*args))
return proxy
@memoize
def genpool(n, m):
if n == 1:
yield [m]
else:
for i in xrange(1, m):
for rest in genpool(n-1, m-i):
yield rest + [i]
def test():
print random.choice(list(genpool(5,50)))
if __name__=='__main__':
test()
A.
More information about the Python-list
mailing list