Domanda

I would like to generate a sequence such that the previously generated element was included in the next element, I am unsure how to do this.

i.e generate the list such that its items were:

where x is just a Sympy symbol

[x,(x)*(x+1),(x)*(x+1)*(x+2)]

rather than [x,x+1,x+2]

I'm thinking something like

k.append(k*(K+o))

but I keep getting a type error

Any help greatly appreciated!

È stato utile?

Soluzione 2

Maybe using a recursive lambda function and a map ?

>>> fact = lambda x: x == 0 and 1 or x * fact(x - 1)
>>> map(fact, range(4))
[1, 1, 2, 6]

and many other ways besides. If you want to return a string define your recursive function to return a string;

def fact(i):
    if i == 0:
        return 'x'
    else:
        return fact(i - 1) + '*(x+%d)' % i

and then

>>> map(fact, range(4))
['x', 'x*(x+1)', 'x*(x+1)*(x+2)', 'x*(x+1)*(x+2)*(x+3)']

and if you're using sympy and think that using strings is an "anti-pattern"

import sympy

def fact(i):
    if i == 0:
        return sympy.Symbol('x')
    else:
        return sympy.Symbol('(x+%d)' % i) * fact(i - 1)

produces

>>> map(fact, range(4))
[x, (x+1)*x, (x+1)*(x+2)*x, (x+1)*(x+2)*(x+3)*x]

Altri suggerimenti

You can use sympy.RaisingFactorial:

import sympy.RaisingFactorial as RF
from sympy.abc import x
length=3
ans = [RF(x,i) for i in xrange(1,length+1)]

Which gives:

[x, x*(x + 1), x*(x + 1)*(x + 2)]

RisingFactorial is probably the best way, especially if you only want the final term, but you can also do

a = [x]
for i in range(1, 5): # Replace 5 with however far up you want to go
    a.append(a[-1]*(x - i))

Assuming there is no ready made function, you can define a polynomial expression (not a Poly) by it's roots pretty easily...

def poly_by_roots(roots, sym):
    return prod(map(lambda x: sym-x, roots))

then apply to a list of roots

polys = [poly_by_roots(range(a,1), x) for a in range(-5,1)]

it's not the most efficient method, that is any which uses the fact that the previous polynomial differs by only (x+i), for example

def poch_list(x,n):
    if n==0:
        return [x]
    else:
        val = poch_list(x,n-1)
        return val + [val[-1]*(x+n)]

which allows symbolic lengths, which may or may not be a good thing.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top