Ask Your Question

ValueError: cannot convert n to int

asked 2017-04-11 01:34:12 +0200

Ruzil gravatar image

I want to do the following


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 flag offensive 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.

kcrisman gravatar imagekcrisman ( 2017-04-11 02:55:13 +0200 )edit

2 Answers

Sort by ยป oldest newest most voted

answered 2017-04-11 21:34:43 +0200

mforets gravatar image

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)
edit flag offensive delete link more


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

kcrisman gravatar imagekcrisman ( 2017-04-12 04:20:04 +0200 )edit

answered 2017-04-11 23:53:25 +0200

nbruin gravatar image

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

sage: function("f")
sage: var("n")
sage: function("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)


sage: exp(sum(log(x),x,1,n))
edit flag offensive delete link 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..

mforets gravatar imagemforets ( 2017-04-12 10:32:45 +0200 )edit

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.

nbruin gravatar imagenbruin ( 2017-04-13 00:05:18 +0200 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower


Asked: 2017-04-11 01:34:12 +0200

Seen: 823 times

Last updated: Apr 11 '17