1
def solver():
    empty_cell = empty_square()
    counter = 0

    if not empty_cell:
        return True

    i,j = empty_cell[0],empty_cell[1]
    for num in range(1,10):
        counter += 1
        if constraint_check(num,i,j):
            sudoku[i][j] = num

            if solver():
                return True

            else:
                sudoku[i][j] = 0

    return False 

Given the code above, how would I implement a counter to count how many iterations the recursive part of the function makes? As can be seen in the code I have attempted something above but I was not able to retrieve this variable to print it out and record the number.

ggorlen
  • 44,755
  • 7
  • 76
  • 106
  • 1
    Have you searched for the problem? What did you find? – NoDataDumpNoContribution Jul 04 '21 at 17:03
  • @CassandraTrotter if you've found a solution, why not share it as a [self answer](https://stackoverflow.com/help/self-answer) so that other people with the same problem can learn from your experience? The point of the site is to curate a repository of knowledge, not purge questions as soon as you get a solution. – ggorlen Jul 05 '21 at 01:15
  • I did not find a solution @ggorlen hence I deleted the contract. The answer provided is severely inadequete. Thus no good answers should enable me to delete the question – Cassandra Trotter Jul 06 '21 at 20:14
  • Hmm -- I might not have been clear. By asking a question, you create a community-owned resource for future visitors with the same problem. Not getting an answer you're satisfied with isn't grounds for deleting a question (unless no answers have upvotes, which is not applicable here). 3 community members felt the answer helped them or was an adequate solution, so the thread remains to help future users. See [this meta thread](https://meta.stackexchange.com/questions/5221/) header "When can't I delete my own post?" – ggorlen Jul 06 '21 at 20:28
  • BTW, [Counting recursive calls of a function](https://stackoverflow.com/questions/41203214/counting-recursive-calls-of-a-function/68277422#68277422) seems to be the canonical thread for this question. The top answer suggests initializing `solver.counter = 0` outside of the function and changing your calls to `solver.counter += 1`. After all the calls resolve, `solver.counter` will hold your result in the enclosing scope. – ggorlen Jul 06 '21 at 21:41

1 Answers1

3

set counter as function parameter -> solver(counter=1) then when calling it again within your function add +1 -> solver(counter+1)

dchoruzy
  • 249
  • 2
  • 8