简体   繁体   English

层 Python 数字总和

[英]Layer Python Sum of Digits

this is my first question around here.这是我在这里的第一个问题。

I've been working on an algorithm that adds the numbers entered until I get a single-digit number, but haven't been able to find a solution for about a week.我一直在研究一种算法,该算法将输入的数字相加,直到我得到一个个位数的数字,但大约一个星期以来一直无法找到解决方案。

for example:例如:

value = 1994
  1. Step = 1+9+9+4 = 23步骤 = 1+9+9+4 = 23
  2. Step = 2+3 = 5步骤 = 2+3 = 5

Try this:尝试这个:

def func(x):
    while x >= 10:
        x = sum([int(c) for c in str(x)])
    return x

print(func(1994))
value = 1994
while len(str(value)) != 1:
  value = sum([int(i) for i in str(value)])

print(value)
5

What's going on?这是怎么回事?

  • initiate value初始值
  • loop if the length of the integer is not equal to one (meaning it's done)如果整数的长度不等于 1,则循环(表示已完成)
  • get a sum of the list of all sub ints inside the int获取 int 中所有子 int 的列表的总和

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM