[英]Repeatedly adding digits of a number until the output has a single digit
I have a two digits number (eg 29) ) and wish to further reduce it to a single digit.我有一个两位数(例如 29))并希望进一步减少到一位数。 How can I do such in python?
我怎么能在 python 中做到这一点? Shall I use the function inside the while loop?
我应该在 while 循环中使用 function 吗? eg
例如
29 -> 11 -> 2
result: [29,11,2]结果:[29,11,2]
x=input('Input digit: ')
result=0
box=[]
def add_two(x):
bz=[]
for i in str(x):
bz.append(int(i))
s=sum(bz)
return s
box=[]
a=0
while len(str(x))>1:
IIUC, you want to reduce a two digit number (29) into a single digit number by performing addition of the tens and units, repeatedly until the number is smaller than 10. IIUC,您想通过执行十位和单位的加法将两位数(29)减少为一位数,重复直到数字小于 10。
NB.注意。 I am using integers here, if you start from a string, first convert to int:
x = int(x)
我这里用的是整数,如果从字符串开始,先转换成int:
x = int(x)
Let's use divmod
by 10 to get the two components:让我们使用
divmod
by 10 来获得两个组件:
divmod(29, 10)
# 2, 9
and sum
them:并将它们
sum
:
sum(divmod(29, 10))
# 11
Now that we have the logic, let's repeat it:现在我们有了逻辑,让我们重复一遍:
x = 29
def reduce(x):
return sum(divmod(x,10))
while x>9:
x = reduce(x)
print(x)
# 2 # 2+9 -> 11 ; 1+1 -> 2
def reduce_until(x):
while x>9:
x = sum(divmod(x,10))
return x
reduce_until(29)
# 2
def reduce_until(x):
while x>9:
total = 0
while x>0:
x,r = divmod(x, 10)
total += r
x = total
return x
reduce_until(56789)
# 56789 -> 35 -> 8
reduce_until(99999999999992)
# 99999999999992 -> 119 -> 11 -> 2
import math
dob_d = 29
while not (0 <= dob_d <= 9):
n = 0
for i in range(math.ceil(math.log10(dob_d))):
n += int(dob_d / (10 ** i) % 10)
dob_d = n
print(dob_d)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.