我正在做a challenge on codewars,我应该在Python中编写数字根函数。我无法弄清楚它为什么不起作用。这是我第一次尝试递归。我真的很想绕过这个。
def digital_root(num):
#Check to see if num has more than one digit
if num > 9:
x = 0
z = 1
#Create an array of the digits in num
digits = [int(d) for d in str(num)]
#Convert string elements in digits[] to ints
for n in digits:
digits[x] = int(x)
x = x + 1
#Add each element in digits[] to digits[0]
for n in digits:
digits[0] = digits[0] + digits[z]
#If digits[0] has more than one digit, then run digital_root with digits[0] in the parameters
if digits[0] > 9:
digital_root(digits[0])
else:
return digits[0]
else:
return num
digital_root(15)
>> Program finished with exit code 0