I have a simple Python script that recursively checks to see if a range of n numbers are factors of a number x. If any of the numbers are not factors I return False, otherwise when the n==1 I would like return True. However I keep returning NoneType and would appreciate suggestions on how to fix this.
#Function
def recursive_factor_test(x, n):
if n==1:
return True
else:
if x % n == 0:
#print "passed {}".format(n)
recursive_factor_test(x,n-1)
else:
return False
#Example Expecting False
print recursive_factor_test(5041,7)
>>False
#Example Expecting True
print recursive_factor_test(5040,7)
>>None
type(recursive_factor_test(5040,7))
>>NoneType
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You don’t ever return the return value of the recursive call:
if x % n == 0:
#print "passed {}".format(n)
return recursive_factor_test(x,n-1)
When you omit the return statement there, your function ends without a return statement, thus falling back to the default None return value.
With the return there, it works:
>>> print recursive_factor_test(5040,7) True
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0