George Soteriou - 1 year ago 81
Python Question

# Python list return 'None'

Code:

``````puzzle1= [
[7,0,0,0,0,0,2,1,8],
[0,4,8,6,2,9,0,0,0],
[0,0,3,0,0,1,0,0,0],
[0,0,7,0,0,8,0,3,2],
[0,0,9,7,0,6,5,0,0],
[6,8,0,1,0,0,7,0,0],
[0,0,0,2,0,0,4,0,0],
[0,0,0,4,1,5,8,7,0],
[3,5,4,0,0,0,0,0,6]
]
def eliminate_values(puzzle):
redo = False
for i in range(9):
for j in range(9):
if puzzle[i][j]==0 or isinstance(puzzle[i][j], list):
puzzle[i][j] = []
for num in range(1,10):
num_check = True;
for x in range(9):
if puzzle[i][x]==num:
num_check = False
if puzzle[x][j]==num:
num_check = False
if i<3:
aa=0
elif i<6 and i>2:
aa=3
else:
aa=6
if j<3:
bb=0
elif j<6 and j>2:
bb=3
else:
bb=6
for a in range(3):
for b in range(3):
if puzzle[a+aa][b+bb]==num:
num_check = False
if num_check:
puzzle[i][j].append(num)
if len(puzzle[i][j]) == 1:
puzzle[i][j] = puzzle[i][j][0]
redo = True;
if redo:
eliminate_values(puzzle)
else:
print(puzzle)
return puzzle

puzzle=eliminate_values(puzzle1)
print(puzzle)
``````

Console:

``````[[7, 9, 6, 3, 5, 4, 2, 1, 8], [1, 4, 8, 6, 2, 9, 3, 5, 7], [5, 2, 3, 8, 7, 1, 9, 6, 4], [4, 1, 7, 5, 9, 8, 6, 3, 2], [2, 3, 9, 7, 4, 6, 5, 8, 1], [6, 8, 5, 1, 3, 2, 7, 4, 9], [8, 7, 1, 2, 6, 3, 4, 9, 5], [9, 6, 2, 4, 1, 5, 8, 7, 3], [3, 5, 4, 9, 8, 7, 1, 2, 6]]
None
``````

I am new to python but i dont understand why print IS working within the function and NOT after it is returned to the main program. (expecting it to print twice but only prints once then 'None')

@tobias_k is right.

In every recursive function you have a base case and a recursive case. The base case is when you reach the end of your recursion and return the final value from your recursive function. The recursive case is where the function calls itself again.

You need to be returning in both cases though.

If you don't, then even if you're eventually hitting your base case, the return value of the base case doesn't get passed up the stack.

i.e.:

``````def recursiveDecrement(x):
if x > 0:
print("Recursive case. x = %s" %x)
recursiveDecrement(x - 1)
print("I should have returned...x = %s" %x)
else:
print("Base case. x = %s" %x)
return x
``````

If I call `recursiveDecrement(5)` my output would be:

``````Recursive case. x = 5
Recursive case. x = 4
Recursive case. x = 3
Recursive case. x = 2
Recursive case. x = 1
Base case. x = 0
I should have returned...x = 1
I should have returned...x = 2
I should have returned...x = 3
I should have returned...x = 4
I should have returned...x = 5
``````

However, once the base case is hit, the method just continues to execute and at the end nothing is returned and x is still equal to 5.

Change your if statement to return in both cases and everything should work.

``````if redo:
return eliminate_values(puzzle)
else:
return puzzle
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download