网络编程
位置:首页>> 网络编程>> Python编程>> python实现水仙花数实例讲解

python实现水仙花数实例讲解

作者:看,月亮在跳舞  发布时间:2021-04-05 11:38:05 

标签: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()

python实现水仙花数实例讲解

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实现水仙花数实例讲解

来源:https://blog.csdn.net/kk_gods/article/details/115007687

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com