'Recursion returning None type? [duplicate]
I wrote a program which finds the super digit of a problem, IE: 9876 = 9+8+7+6 = 30 = 3+0 = super digit = 3 This works fine whenever the program doesn't call on itself, but in the case above, I will get a final integer value of 3, and it will print as such, but when I go to return it, it returns None. Im wondering why this might be the case?
here is the code:
def super_digit(n):
sup_Digit = 0
intArray = [int(i) for i in str(n)]
for i in range(len(intArray)):
sup_Digit += intArray[i]
if sup_Digit and sup_Digit < 10:
return int(sup_Digit)
else:
super_digit(sup_Digit)
and here is my test case:
from unittest import TestCase
tc = TestCase()
tc.assertEqual(super_digit(5), 5)
tc.assertEqual(super_digit(30), 3)
tc.assertEqual(super_digit(9876), 3)
tc.assertEqual(super_digit(11111111111111), 5)
tc.assertEqual(super_digit(12345678901234567890), 9)
Solution 1:[1]
You forgot the return statement:
def super_digit(n):
sup_Digit = 0
intArray = [int(i) for i in str(n)]
for i in range(len(intArray)):
sup_Digit += intArray[i]
if sup_Digit and sup_Digit < 10:
return int(sup_Digit)
else:
return super_digit(sup_Digit)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mrCarnivore |
