Nuno Fernandes
Nuno Fernandes

Reputation: 31

Can't count iterations on double for loop in python

I am having trouble implementing a counter to count over iterations on a double for loop.

My code is the following:

def encode(mat,l,c,mode,m):
    sampleCount = 0
    for i in range(l):
        for j in range(c):
            sampleCount += 1

    print(sampleCount)

My program calls this function with values of "l" of 720 and 360 and values of "c" of 1280 and 640 respectively. What I was expecting was sampleCount values of 921600 and 230400. However, it prints either 1279 or 639. Also, when i tested printing i and j like this:

for i in range(l):
    print(i)
    for j in range(c):
        print(j)

What I get is the program printing all the i values, from 0 to l-1 and only then printing the j values from 0 to c-1.

Can anyone tell me what I may be doing wrong? Thanks in advance!

Edit: Pasted code without identation

Edit 2: Tried commenting everything after sampleCount += 1. In that case, i obtain the expected results. And it continues to work well if i uncomment the following two lines of code. However, when i tried uncommenting more than 3 lines of code, it goes back to misbehaving. In short, it works when the code is like this:

def encode2(mat,l,c,mode,m):
    sampleCount = 0
    for i in range(l):
        for j in range(c):
            sampleCount += 1
            a = 0
            b = 0
            # c = 0
            # x = 0
            # if (i == 0 & j == 0):
            #     a = 0
            #     b = 0
            #     c = 0
         ...  ...

And misbehaves again if the code is like this:

def encode2(mat,l,c,mode,m):
    sampleCount = 0
    for i in range(l):
        for j in range(c):
            sampleCount += 1
            a = 0
            b = 0
            c = 0
            # x = 0
            # if (i == 0 & j == 0):
            #     a = 0
            #     b = 0
            #     c = 0
         ...   ...

Upvotes: 0

Views: 102

Answers (1)

Vaibhav Jadhav
Vaibhav Jadhav

Reputation: 2076

I got the following result when I ran the same code:

def encode(l,c):
    sampleCount = 0
    for i in range(l):
        for j in range(c):
            sampleCount += 1

    print(sampleCount)
encode(360,640)

Result: 230400

def encode(l,c):
    sampleCount = 0
    for i in range(l):
        for j in range(c):
            sampleCount += 1

    print(sampleCount)
encode(720,1280)

Result: 921600

The same is your expectation?

Upvotes: 1

Related Questions