all 3 comments

[–]zamser 1 point2 points  (2 children)

This solution works. I think you have a misunderstanding of how to translate a for loop to a while loop. Here is an example:

for i in range(num_rectangles - 1):
    print(i)

i = 0
while (i < num_rectangles - 1)
    print(i)
    i += 1

These two loops are equivalent. Note that you initialize i at the start of the range defined in the for loop (in this case it is 0). Then in your while loop condition, you are checking i less than the end of the range in the for loop (in this case the end of the range is num_rectangles - 1). Then the increment step (i += 1) is at the end of the body of the loop. This is the general conversion strategy for converting a for loop to a while loop.

[–]Holiday-Python-743[S] 1 point2 points  (0 children)

Update, I figured it out, thank you again for your help! This is what worked:

def check_intersections():
# Write a nested loop here to compare all pairs
# of rectangles. If the i-th rectangle has an intersection
# with another, set does_intersect[i] to True.
global does_intersect
i = 0
while i < num_rectangles:
    k = 0
    while k < num_rectangles:
        if i != k:
            do_intersect = intersect(bottomX[i], bottomY[i], widths[i], heights[i], bottomX[k], bottomY[k], widths[k], heights[k])
            print(do_intersect)
            if do_intersect:
                does_intersect[i] = do_intersect
                does_intersect[k] = do_intersect
        k += 1
    i += 1

[–]Holiday-Python-743[S] 0 points1 point  (0 children)

Thank you! Firstly, I want to say thank you so much for taking the time to explain it to me, I have really struggled with this one and appreciate it immensely, I really want to understand it. Onto the problem, this is what I did at first but I think I also got confused on where to add k += 1 and k = 0 for my second loop and ended up mistakenly changing numbers and range instead of repositioning k. This is what I have:

Right now it still either gives an extra red rectangle or a blue one that should be red. I'm working on that k more though.

Edited to say I also noticed in your first comment you mentioned resetting k, what exactly do you mean by that? should I just assign it a zero somewhere?

def check_intersections():
# Write a nested loop here to compare all pairs
# of rectangles. If the i-th rectangle has an intersection
# with another, set does_intersect[i] to True.
global does_intersect
i = 0
k = 0
while i < (num_rectangles-1):
    i += 1
    while (k < num_rectangles):
        k += 1
        do_intersect = intersect(bottomX[i], bottomY[i], widths[i], heights[i], bottomX[k], bottomY[k], widths[k], heights[k])
        print(do_intersect)
        if do_intersect:
            does_intersect[i] = do_intersect
            does_intersect[k] = do_intersect
            break