question on list comprehensions
Bengt Richter
bokr at oz.net
Mon Oct 18 07:02:48 EDT 2004
On Sun, 17 Oct 2004 20:25:54 -0400, "Terry Reedy" <tjreedy at udel.edu> wrote:
>
>"Alex Martelli" <aleaxit at yahoo.com> wrote in message
>news:1gltsqx.3sh0uedtr3f0N%aleaxit at yahoo.com...
>> If I recall correctly, you can generally find closed-form solutions for
>> summations of polynomials in i.
>
>Yes, as with integrals, the sum of an nth degree poly is (n+1)th degree.
>The n+2 coefficients for the sum from 0 to k can be determined by actually
>summing the poly for each of 0 to n+1 and equating the n+2 partial sume to
>the result poly (with powers evaluated) to get n+2 equations in n+2
>unknowns. Even with integral coefficients in the poly to be summed, the
>coefficients are generally non-integral rationals and can get pretty nasty
>to calculate, so for exact results, it may well be easier and faster to
>write and run a program.
>
Got curious, so I automated creating a polynomial based on an integer series:
>>> from coeffs import getlambda
>>> getlambda([0,1,2,3])
'lambda x: x'
>>> getlambda([1,2,3])
'lambda x: x +1'
>>> L = [sum(xrange(i)) for i in xrange(1,10)]
>>> L
[0, 1, 3, 6, 10, 15, 21, 28, 36]
>>> getlambda(L)
'lambda x: (x**2 +x)/2'
>>> f = eval(getlambda(L))
>>> [f(x) for x in xrange(9)]
[0, 1, 3, 6, 10, 15, 21, 28, 36]
>>> L2 = [sum([i**2 for i in xrange(j)]) for j in xrange(1,10)]
>>> L2
[0, 1, 5, 14, 30, 55, 91, 140, 204]
>>> f2 = eval(getlambda(L2))
>>> [f2(x) for x in xrange(9)]
[0, 1, 5, 14, 30, 55, 91, 140, 204]
>>> getlambda(L2)
'lambda x: (2*x**3 +3*x**2 +x)/6'
>>>
Now we'll try an arbitrary series:
>>> f3 = eval(getlambda([3,1,1,0,3,5]))
>>> [f3(x) for x in xrange(6)]
[3, 1, 1, 0, 3, 5]
>>> getlambda([3,1,1,0,3,5])
'lambda x: (-1080*x**5 +13200*x**4 -55800*x**3 +98400*x**2 -69120*x +21600)/7200'
Maybe I'll clean it up some time ;-)
It's a simultaneous equation solver using my exact decimal/rational class for math,
and then formatting the lambda expression for the nonzero polynomial coefficients.
Not very tested, but seems to work.
Regards,
Bengt Richter
More information about the Python-list
mailing list