0

I am attempting to create a nested for loop where the inner loop will have a different range the first time the loop runs and then use a different range for each subsequent loop.

The program is a sudoku solver. And it works by taking a position on the 9x9 board (board[k][l]), checking a condition, and then moving to the board position directly to the left (board[k][l-1]).

If l is 0 than we need to move to the previous row (k-1) and the farthest position to the right where l equals 8.

The problem I am having is on the first iteration of the inner loop the loop will not always begin with l equal to 8.

For example a user my select the square board[3][3]. The function should then check board[3][2] then board[3][1] then board[3][0] then board[2][8]

etc.

The code below only works if l=8

for i in range(k, -1, -1):
    for j in range(l, -1, -1):

For clarity, I can achieve the desired result using multiple for loops, but I am trying to make this code more concise:

k = user selection
l = user selection

for j in range(l, 0, -1):
    test(k,j)
for i in range(k-1, -1, -1):
    for j in range(9, 0 , -1):
        test(i,j)

I don't like this for two reasons, first we encounter a problem if either k or l starts at 0, second it seems unnecessary to use two for loops here.

1
  • @DeveshKumarSingh sorry if it wasn’t clear k does not alway =9 and l does not always = 9 Commented May 6, 2019 at 16:41

2 Answers 2

1

Isn't it just a matter of putting an if statement in there?

>>> k = 8
>>> l = 3
>>> run_one = True
>>> for i in range(k, -1, -1):
...  if run_one:
...     run_one = False
...     for j in range(l, -1, -1):
...       print(i, j)
...  else:
...     for j in range(8, -1, -1):
...       print(i, j)
... 
8 3
8 2
8 1
8 0
7 8
7 7
7 6
7 5
7 4
7 3
7 2
7 1
7 0
6 8
6 7
6 6
6 5
6 4
6 3
6 2
6 1
6 0
5 8
5 7
5 6
5 5
5 4
5 3
5 2
5 1
5 0
4 8
4 7
4 6
4 5
4 4
4 3
4 2
4 1
4 0
3 8
3 7
3 6
3 5
3 4
3 3
3 2
3 1
3 0
2 8
2 7
2 6
2 5
2 4
2 3
2 2
2 1
2 0
1 8
1 7
1 6
1 5
1 4
1 3
1 2
1 1
1 0
0 8
0 7
0 6
0 5
0 4
0 3
0 2
0 1
0 0
>>> 
Sign up to request clarification or add additional context in comments.

Comments

0

You can manage this in one single loop if you use an extra if (or a ternary expression like here):

l = 2
k = 5
for i in range(l, -1, -1):
  max = k if i == l else 9
  for j in range(max, 0, -1):
    print("{},{}".format(i,j))

gives:

2,5
2,4
2,3
2,2
2,1
1,9
1,8
1,7
1,6
1,5
1,4
1,3
1,2
1,1
0,9
0,8
0,7
0,6
0,5
0,4
0,3
0,2
0,1

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.