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]