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!
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]