Ask Your Question

Different results with for loop and while loop

asked 2019-11-15 16:35:56 -0600

ShreevatsaR gravatar image

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:

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:
    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.

edit retag flag offensive close merge delete


ShreevatsaR gravatar imageShreevatsaR ( 2019-11-15 19:07:12 -0600 )edit

1 answer

Sort by ยป oldest newest most voted

answered 2019-11-15 16:38:34 -0600

ShreevatsaR gravatar image

Figured out the the reason as well: with

for w in range(1, N):

the type of w is int, and so is the type of h inside the inner loop in fill. So something like w/(w+h) uses integer division (on ints), giving 0.

On the other hand, with

w = 1
while w < N:
    w += 1

the type of w is Integer, so w/(w+h) results in a proper fraction and not 0.

edit flag offensive delete link more


You can use srange to get a range of Integer type integers.

nbruin gravatar imagenbruin ( 2019-11-15 20:18:26 -0600 )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: 2019-11-15 16:35:56 -0600

Seen: 140 times

Last updated: Nov 15 '19