pythonfor-loop

What the differences between these 3 for loops?


def generate_coor(dimension_x,dimension_y):
    x,y=int(dimension_x/2),int(dimension_y/2)
    for i in range(0, x + 1):
        print(x)
        x=x+1

generate_coor(100,27)

The above code does terminate.

def generate_coor(dimension_x,dimension_y):
    x,y=int(dimension_x/2),int(dimension_y/2)
    for i in range(0, x + 1):
        for j in range(0, y + 1):
            print(y)
            y=y+1

generate_coor(100,27)

The above code does not terminate

def generate_coor(dimension_x,dimension_y):
    x,y=int(dimension_x/2),int(dimension_y/2)
    for i in range(0, y):
        for j in range(0, y + 1):
            print(y)
            y=y+1

The above code does terminate

What the differences between these 3 examples? According to the code, each iteration for x or y should be increase by 1 hence the loop should not terminate but some terminate, some does not?


Solution

  • All loops will terminate, but the time to do so depends on the value you enter as parameter inputs.

    What happens in your 2nd example :

    def generate_coor(dimension_x,dimension_y):
        x,y=int(dimension_x/2),int(dimension_y/2)
        for i in range(0, x + 1):
            for j in range(0, y + 1):
                print(y)
                y=y+1
    

    is that your nested loop for j in range(0, y + 1) is repeating itself for each iteration of the first loop for i in range(0, x + 1). This is particularly time consuming in your case with generate_coor(100,27) being given the CPU time required to execute the function will be exponential with respect to your two integer inputs.

    If you take lower values, e.g. generate_coor(10,10), you'll see the function exiting.