Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading