Python Forum

Full Version: Am i doing something wrong with this piece of code
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i am trying to get an output as follows:
Quote:1 1 1
1 1 2
1 1 3
1 2 2
1 2 3
1 2 1
1 3 3
1 3 1
1 3 2
2 2 2
2 2 3
2 2 1
2 3 3
2 3 1
2 3 2
2 1 1
2 1 2
2 1 3
3 3 3
3 3 1
3 3 2
3 1 1
3 1 2
3 1 3
3 2 2
3 2 3
3 2 1
with the following code
for i in range(1, 4):
    for j in range(i, i + 3):
        if (j > 3):
            jdisplay = j % 3

        else:
            jdisplay = j
        for k in range(j,j+3):
            if(k>3):
                kdisplay=k%3
            else:
                kdisplay=k
            print(i,jdisplay,kdisplay)
but i am getting output as below
Quote:1 1 1
1 1 2
1 1 3
1 2 2
1 2 3
1 2 1
1 3 3
1 3 1
1 3 2
2 2 2
2 2 3
2 2 1
2 3 3
2 3 1
2 3 2
2 1 1
2 1 2
2 1 0
3 3 3
3 3 1
3 3 2
3 1 1
3 1 2
3 1 0
3 2 2
3 2 0
3 2 1

The difference is the 0 being printed instead of 3 (in bold) in the 3rd column, in the piece of code i have written i have asked it to do a modulo division only if the number is greater than 3, but is it doing even if it is equal to 3? or am i missing something
I'm guessing because theres no remainder.
for k in range(j,j+3):
Starts at index 3 and ends on 6.
6%3 = 0
You could try checking it first and assign 3 if it has no remainder.
There's probably a better way of doing it but this should work.
kdisplay= k%3 if (k%3) else 3

for i in range(1, 4):
    for j in range(i, i + 3):
        if (j > 3):
            jdisplay = j % 3
 
        else:
            jdisplay = j
        for k in range(j,j+3):
            kdisplay= k%3 if (k%3) else 3
            print(i,jdisplay,kdisplay)
wow, this works well, and oh my god your first post is the reply to my question...awesome ..

but this seems to be hard coded approach, is there a better way of doing it?
I've been hanging around the forum for a few weeks reading different posts but forgot to register ha.