# ValueError: cannot convert n to int

I want to do the following

var('n')

prod([k for k in range(1,n)])

But I get the following error: ValueError: cannot convert n to int

Is there some way to do this that does not involve writing a for loop?

edit retag close merge delete

Are you trying to do a symbolic product? If n does not have a specific value then you won't get factorial(n-1) which I suppose is what you want.

Sort by » oldest newest most voted

SymPy's product function does transform that particular symbolic product into the factorial:

sage: from sympy import product, symbols
sage: i, n = symbols('i, n')
sage: product(i, (i, 1, n-1))
factorial(n - 1)


It makes me think that for prod it is a feature which hasn't been implemented but perhaps i'm mistaken. Note that sum has a nicer behavior: for instance sum(1/i, i, 1, n) returns harmonic_number(n).

One alternative is not using prod but just factorial(n-1), as already suggested by kcrisman. Another alternative is to define a Python's lambda function (more on this here), as in:

sage: someProduct = lambda n : prod([i for i in range(1, n)])
sage: someProduct(10)
362880

more

The lambda might be what this user needs, that is a good idea.

The symbolic product exists somewhere already (probably in Maxima?), so with some trickery you can get something that looks like it:

sage: function("f")
f
sage: var("n")
n
sage: function("f")
f
sage: P=exp(sum(log(f(x)),x,1,n-1)); P
product(f(x), x, 1, n - 1)


At this point, P.operator is just a formal object: sage itself doesn't know anything about it:

sage: product=P.operator()
sage: product(x,x,1,n).simplify_full()
product(x, x, 1, n)


whereas

sage: exp(sum(log(x),x,1,n))
factorial(n)

more

interesting. it would be nice to have these symbolic products though, similarly to the symbolic sum. an application would be to represent / compute infinite products..

It's just a matter of hooking them in! As the answers show, sympy and maxima already have them. Maxima can't do much with them, though.