python实现水仙花数

python实现水仙花数,第1张

概述转:python实现水仙花数 1、什么是水仙花数?水仙花数(Narcissisticnumber)也被称为超完全数字不变数(pluperfectdigitalinvariant,PPDI)、自恋数、自幂数、阿姆斯壮数或阿姆斯特朗数(Armstrongnumber),水仙花数是指一个3位数,它的每个位上的数字的3次幂之和等于它本身(例如:1^3+

转:

python实现水仙花数

 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)

转:

python实现水仙花数

总结

以上是内存溢出为你收集整理的python实现水仙花数全部内容,希望文章能够帮你解决python实现水仙花数所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1186620.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-03
下一篇 2022-06-03

发表评论

登录后才能评论

评论列表(0条)

保存