Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Different results with for loop and while loop

While writing a Sage script, I ran into a strange case where code worked correctly with specific constants, but when I looped over them in a for loop, it no longer worked. After trying this and that, I found that a while loop did not have this problem! As this felt very strange, recording the question here as a possible "gotcha".

Here's the code:

var('z')
from collections import defaultdict
p = defaultdict(dict)

N = 30
for h in range(N): p[0][h] = z**h

def fill(w):
    for h in range(N - w):
        p[w][h] = w/(w+h)*p[w-1][h+1] + h/(w+h)*(p[w][h-1] if h>=1 else 0)

## This doesn't work:
# for w in range(1, N): fill(w)
## Instead we need the below:
w = 1
while w < N:
    fill(w)
    w += 1

In short, the problem is that for w in range(1, N): ... results in all zero polynomials, while w = 1; while w < N: ... does not.