0

My prompt: "Write a program that uses two nested while loops to print off the rows and columns of a 3x3 grid (numbered 1 to 3), excluding the cells along the diagonal (i.e., where the row and column have the same value). The first three rows of your program's output should look like this:

1 2
1 3
2 1

I have coded it pretty well so far, but I am stuck with one extra unwanted output. How do I remove it?

row = 0
while row < 3:
    col = 0
    row += 1
    while col < 3:
        col += 1
        if row == col:
            col += 1
        print (row, col)

expected result should be:

  1 2  
  1 3
  2 1
  2 3
  3 1
  3 2

but 3 4 is included as well.

2
  • Could you clarify what your input is? What I'm imagining this 3x3 grid to look like doesn't square with your expected output. Commented Sep 22, 2019 at 7:27
  • @nmpauls Hey, thanks for replying! I just want the coordinates as described in the post; minus the diagonals i.e 1 2, 1 3, 2 1, 2 3, 3 1, 3 2 Commented Sep 22, 2019 at 7:31

2 Answers 2

1

Your if condition should change to print (i, j) only if they are not equal.

i = 1 
while i < 4:
    j = 1
    while j < 4:
        if i != j:
            print(i, j)
        j += 1
    i += 1
# 1 2
# 1 3
# 2 1
# 2 3
# 3 1
# 3 2

Also I've started iteration from 1 instead of 0 because this looks a little better organised to me.

P.S., the more idiomatic way of doing this would be using a list comprehension.

[(i, j) for i in range(1, 4) for j in range(1, 4) if i != j]
# [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you @cs95 I will definitely try this format as well!
0

It's because where row and col both equals to 3, you are increasing col to 4, and print. Modify to:

row = 0
while row < 3:
    col = 0
    row += 1
    while col < 3:
        col += 1
        if row != col:
            print (row, col)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.