Python练习题-013

题目-013:打印出所有的"水仙花数",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数本身。例如:153是一个"水仙花数",因为153=1的三次方+5的三次方+3的三次方。

  • 分析每个数分解出个位,十位,百位,然后做比较处理
  • Python版本:Python 3.6.5

   代码1:使用math中的函数,math.ceil(f) #向上取整;math.floor(f) #向下取整;round(f) #四舍五入

#! usr/bin/python
#! -*- coding: utf-8 -*-

import math
def narcissistic_number( min=100,max=999 ):
    arr = []
    for n in range(min,max+1):
        i = int(math.floor(n/100))
        j = int(math.floor(n/10%10))
        k = int(n%10)
        if ( n == i**3+j**3+k**3 ):
            arr.append(n)

    print(arr)

narcissistic_number()
[153, 370, 371, 407]

   代码2:另一种解法,使用str类型的特性

#! usr/bin/python
#! -*- coding: utf-8 -*-

def narcissistic_number2( min=100,max=999 ):
    arr = []
    for m in range(min,max+1):
        n = str(m)
        if ( m == int(n[0])**3+int(n[1])**3+int(n[2])**3 ):
            arr.append(m)
    print(arr)

narcissistic_number2()
[153, 370, 371, 407]



你可能感兴趣的:(python)