Infinite Loop when it's supposed to end because it has a clear condition that should be met

Question:

So the objetive is that the list names sorted_resistances appends its first 12 items to the blocks_A[0] and then skip 12 items and pass the next 12 to the blocks_A[1] and so on until the length of blocks_A[28] equals 12. The problem is that its the while loop never ends when it should because blocks_A[28] should have 12 elements.(Its the while len(blocks_A[28]) < 12 loop)

from math import *

blocks_B = []
y = 0
while y < 29:
    y = y + 1
    block_y = []
    blocks_B.append(block_y)

blocks_A = []
y = 0
while y < 29:
    y = y + 1
    block_y = []
    blocks_A.append(block_y)

with open("file.txt") as file_in:

    list_of_resistances = []
    for line in file_in:
        list_of_resistances.append(int(line))
        sorted_resistances = sorted(list_of_resistances)

    while len(blocks_A[28]) < 12:
        z = 0
        w = 11
        x = 0
        for y in sorted_resistances[z:w]:
            blocks_A[x].append(y)
            blocks_A[x].sort()
        if len(blocks_A[x]) == 12:
            x = x + 1
            z = z + 24
            w = w + 24


print(blocks_A)
print(blocks_B)

Asked By: Joao

||

Answers:

Indexing from 0:11 stops at 10, so it only gives you 11 elements, so you never step forward the x.

You are also resetting the x to zero every iteration of the while loop. Put the x = 0 along with the w and z assignements before the while loop.

Answered By: Michael Cao

The issue with the code is with the way it increments the z and w variables within the loop. The values of z and w should increase by 12 after each iteration, but they’re increasing by 24 instead. This means that the loop will never end as z and w will never reach the end of the sorted_resistances list.

Answered By: Pranav Sharma
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.