python - 使用递归的数字的数字根
问题描述
我正在编写一个递归函数来计算给定数字的数字根:
def digital_root(num):
sum = 0
while num > 0:
sum += num % 10
num = num // 10
while sum > 10:
sum = digital_root(sum)
return sum
我不确定第二个while
是否应该用if
语句替换,如果是,为什么?(如果没有,为什么不呢?)
当我尝试两个版本时,返回值是相同的。例如,对于数字10598
,它们的输出都是5
。
解决方案
如果它厌倦了人们不接受我的解决方案,请确保接受答案,当它对他们有用时
def digital_root(num):
#Base case for recursion.
# recursion always needs a base case
if len(str(num)) == 1:
return num
#Get sum of num by turning it into a string and looping through it,
#adding each index one by one
sum = 0
for i in str(num):
sum += int(i)
#get the digital root of the sum
return digital_root(sum)
def main():
print(digital_root(27518))
if __name__ == '__main__':
main()
给你
推荐阅读
- wpf - 如何使用 SVG 格式的矢量图像样式进行操作?
- autodesk-forge - AutoDesk Forge Viewer:使用 SVF 的 URN 加载模型
- javascript - MQTT.js 如何使用 vuex 挂钩连接状态
- java - 由于逻辑错误,允许相同的树集值
- ruby-on-rails - 如何使用 Ruby 中的路径裁剪图像?
- regex - 正则表达式:组的匹配补码
- php - 全部重写为 1 个域,Joomla 管理员除外
- mysql - 在 MySQL 中创建存储过程时出现错误 1064 (42000)
- amazon-web-services - 打包程序“source_ami_filter”中的“所有者”字段有什么作用?
- asp.net-core - 如何从 Blazor WASM 中的类调用 StateHasChanged() / NotifyAuthenticationStateChanged