我嘗試實現查找數字的數字根的函數(它是數字中所有數字的遞歸和。)但由于某種原因,如果函數對自身進行遞歸調用,它不會返回任何內容import functoolsdef digital_root(n): r=functools.reduce(lambda x,y:int(x)+int(y),list(str(n))); if r//10<1: return r else: digital_root(r)
3 回答

倚天杖
TA貢獻1828條經驗 獲得超3個贊
您沒有在 else 子句中返回任何值,因此它給出 None
def digital_root(n):
r=functools.reduce(lambda x,y:int(x)+int(y),list(str(n)));
if r//10<1:
return r
else:
return digital_root(r)
更具可讀性的形式是:
def root(n):
d_sum = 0
for i in str(n):
d_sum += int(i)
if dsum<10:
return d_sum
return root(d_sum)
沒有遞歸:
def root(n):
while n > 9:
n = sum(map(int, str(n)))
return n

莫回無
TA貢獻1865條經驗 獲得超7個贊
除了缺少 之外return
,您還沒有查找簡化的封閉式算法:
return 9 if (r % 9 == 0) else (r % 9) # Parentheses are unneeded, but added for readability
數字和的“老派”名稱是“casting out nines”。您采用該數字的?;鶖?code>b-1,其中b
是原始數字基數。十進制為 9,十六進制為 15,等等。
- 3 回答
- 0 關注
- 150 瀏覽
添加回答
舉報
0/150
提交
取消