I know that return statement will make the execution jump out of the function. So I have a concern with the following program which solves Suduko puzzle recursively:
class Puzzle:
def __init__(self):
self.loop = 0
self.answer = 0
self.done = False
def same_row(self,i,j):
return i/9 == j/9
def same_col(self,i,j):
return (i-j)%9 == 0
def same_block(self,i,j):
return (i/27 == j/27 and i%9/3 == j%9/3)
def print_format(self,a):
for row in range(9):
for col in range(9):
print '%s ' % a[9*row + col],
print ''
def solve(self,a):
self.loop += 1
if self.answer == 1 and self.loop>100000 or self.answer == 2:
self.done = True
i = a.find('0')
if i == -1:
self.answer += 1
print 'after %d loops worked out solution %d:' % (self.loop, self.answer)
self.print_format(a)
return
excluded_num = set()
for j in range(81):
if self.same_row(i,j) or self.same_col(i,j) or self.same_block(i,j):
excluded_num.add(a[j])
for m in '123456789':
if m not in excluded_num:
if self.done:
return
print 'xxx loop %d' % self.loop
self.solve(a[:i]+m+a[i+1:])
if __name__ == '__main__':
puz = Puzzle()
sudoku="060593000901000500030400090108020004400309001200010609080006020004000807000000000"
puz.solve(sudoku)
This is an program to solve a sudoku puzzle, I check the output I find a question I cannot understand why, the output is something like:
Could anyone tell me why the 'xxx loop 125' and 'xxx loop 175' are getting printed? As there is return statement in line 32, why the execution still went down and gets them printed? Many thanks