我必须找到指数数字的总和,这是用户的输入。我的输出应该是这样的。如何将列表元素显示为添加?
结果:33 = 27 = 2 +7 = 9
当数字像3 ^( - 20)时,它得到的结果如2.867972e-10如何找到其数字的总和?
答案 0 :(得分:1)
另一种解决方案可能有效,但同时也不容易理解。就个人而言,我更喜欢reduce
functools
来汇总与您相同的金额。看看:
from functools import reduce
num = 0.00003 ** -10
print("num = %f" % num)
# Remove the exponent (does nothing if there's no exponent)
num = str(num).split('e')[0]
print("Without exponent: %s" % num)
# Remove the point
num = num.replace('.', '')
print("Without the point: %s" % num)
# Calculate the sum
digit_sum = reduce((lambda x, y: int(x) + int(y)), list(num))
print("Sum: %s" % digit_sum)
答案 1 :(得分:0)
您可以在list-comprehension
上使用generator
:
sum(int(i) for i in str(int(input("what's the first number"))**int(input("what's the second number"))))
要以您想要的方式显示,您可以:
base = int(input("what's the base?"))
exponent = int(input("what's the exponent?"))
result = base ** exponent
digits = [int(i) for i in str(result)]
print(base,"^",exponent,"=",'+'.join(list(str(result))),"=",sum(digits))
答案 2 :(得分:-1)
a=3
b=4
s=a**b
sl=str(s).split('e')[0].replace('.','')
z=int(sl)%9
print('{}^{}={}={}={}'.format(a,b,s,'+'.join(sl),z if z else 9))
# output 3^4=81=8+1=9