Kevin Jin Kevin Jin - 25 days ago 9
Python Question

Function is returning null instead of the array object, looks very simple

I have two methods, spiralOrder and recurSpiral where spiralOrder is my main method. It's weird because print spiralArray, but when I return spiralArray on the next line, it returns null. I feel like I'm missing something very simple. Thanks

class Solution(object):
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
spiralArray = []
final = self.recurSpiral(matrix, spiralArray)
return final

def recurSpiral(self, matrix, spiralArray):
print matrix
if(len(matrix) == 0 or len(matrix[0]) == 0):
print spiralArray
return spiralArray

if(len(matrix) <= 2 or len(matrix[0]) <= 2):
self.firstThree(matrix, spiralArray)
return spiralArray

spiralArray = self.firstThree(matrix, spiralArray)
print spiralArray

notFirst = False
for l in reversed(matrix[1:]):
if(notFirst):
spiralArray.append(l[0])
else:
notFirst = True
print spiralArray
self.recurSpiral(matrix[1:-1][1:-1], spiralArray)

def firstThree(self, matrix, spiralArray):

for i in matrix[0]:
spiralArray.append(i)

notFirst = False
for j in matrix:
if(notFirst):
spiralArray.append(j[len(matrix[0])-1])
else:
notFirst = True

notFirst = False
for k in reversed(matrix[len(matrix)-1]):
if(notFirst):
spiralArray.append(k)
else:
notFirst = True

print spiralArray
return spiralArray

Answer Source

You are missing a return statement at the end of your function. Instead of:

self.recurSpiral(matrix[1:-1][1:-1], spiralArray)

It should be:

return self.recurSpiral(matrix[1:-1][1:-1], spiralArray)

Otherwise, your function will return None if the end of the function is reached on that path.