1 | initial version |
I will elaborate on the comment, which is correct; you could use
sage: def N(d,n):
....: if n==1:
....: return 1
....: else:
....: return sum(N(d,i) for i in range(1,n))
Ordinarily, this should have just returned some sort of evident error that you couldn't do it (such as below). But because of a subtlety in how you defined your function, instead you never actually discovered this in your sum. Your sum instead kept returning itself when n=2
, so you got a RuntimeError
about infinite recursion.
If you do sum?
in the terminal or notebook, you should get documentation that includes this:
Warning: This function only works with symbolic expressions. To
sum any other objects like list elements or function return
values, please use python summation, see
http://docs.python.org/library/functions.html#sumIn particular,
this does not work:
sage: n = var('n')
sage: mylist = [1,2,3,4,5]
sage: sum(mylist[n], n, 0, 3)
Traceback (most recent call last):
...
TypeError: unable to convert n to an integer
Use python "sum()" instead:
sage: sum(mylist[n] for n in range(4))
10
Also, where does d
occur in your function? It seems to be a dummy variable in the truest sense of the word - completely silent, that is.
2 | No.2 Revision |
I will elaborate on the comment, other answer, which is correct; you could use
sage: def N(d,n):
....: if n==1:
....: return 1
....: else:
....: return sum(N(d,i) for i in range(1,n))
Ordinarily, this should have just returned some sort of evident error that you couldn't do it (such as below). But because of a subtlety in how you defined your function, instead you never actually discovered this in your sum. Your sum instead kept returning itself when n=2
, so you got a RuntimeError
about infinite recursion.
If you do sum?
in the terminal or notebook, you should get documentation that includes this:
Warning: This function only works with symbolic expressions. To
sum any other objects like list elements or function return
values, please use python summation, see
http://docs.python.org/library/functions.html#sumIn particular,
this does not work:
sage: n = var('n')
sage: mylist = [1,2,3,4,5]
sage: sum(mylist[n], n, 0, 3)
Traceback (most recent call last):
...
TypeError: unable to convert n to an integer
Use python "sum()" instead:
sage: sum(mylist[n] for n in range(4))
10
Also, where does d
occur in your function? It seems to be a dummy variable in the truest sense of the word - completely silent, that is.