1、什么是水仙花数?
水仙花数(Narcissistic number)也被称为超完全数字不变数(pluperfect digital invariant, PPDI)、自恋数、自幂数、阿姆斯壮数或阿姆斯特朗数(Armstrong number),水仙花数是指一个 3 位数,它的每个位上的数字的 3次幂之和等于它本身(例如:1^3 + 5^3+ 3^3 = 153)
详见:水仙花数-百度百科
2、实现:
def number_daffodils(m=100, n=1000):
if type(m) is int and type(n) is int and 100 <= m < n <= 1000:
daffodils = []
for num in range(m, n):
a = [int(s) for s in str(num)]
"""
计算个、十、百位数
x = int(num/100) # 百位数
y = int(num/10) % 10 # 十位数
z = num % 10 # 个位数
将整数按位拆分
a = list(str(num))
a = list(map(eval, str(num)))
"""
if num == a[0] ** 3 + a[1] ** 3 + a[2] ** 3:
daffodils.append(num)
if len(daffodils) == 0:
print("No number of daffodils")
else:
print(" ".join(str(i) for i in daffodils))
elif type(m) is not int or type(n) is not int:
raise Exception('参数类型错误')
else:
raise Exception('参数超出范围')
number_daffodils()
3、懒人法:列表推导式
a = [i * 100 + j * 10 + k for i in range(1, 10) for j in range(0, 10) for k in range(0, 10) if i * 100 + j * 10 + k == i ** 3 + j ** 3 + k ** 3]
print(a)
本文转自SDK社区:https://www.sdk.cn
www.juhe.cn