Day9:打印出来所有的水仙花数
#水仙花数:一个三位数,其各位数字的立方和等于该数据本身
#例如153就是一个水仙花数,因为153 = 1^3 + 5^3 + 3^3
方法一:先将数字转换为字符串形式,将每位依次放进列表里
1 def num(): 2 3 n = 100 4 list_1 = [] 5 while n <= 999: 6 list = [int(i) for i in str(n)] 7 if list[0]**3 + list[1] ** 3 + list[2] ** 3 == n: 8 list_1.append(n) 9 n += 1 10 return list_1 11 12 13 print(num()) 14 15 #或者转换为for循环 16 def num(): 17 list_1 = [] 18 for n in range(100,1000): 19 list = [int(i) for i in str(n)] 20 if list[0]**3 + list[1] ** 3 + list[2] ** 3 == n: 21 list_1.append(n) 22 return list_1 23 24 25 print(num())
输出结果:
方法二:该方法可以找出来所有类似的数字,四位数(1634 = 1^4 + 6^4 + 3^4 + 4^4),五位数等等
1 def num(): 2 list_1 = [] 3 for i in range(100,1000000): 4 s = 0 5 number = str(i) 6 for j in number: 7 s += int(j) ** len(number) 8 if s == i: 9 list_1.append(i) 10 return list_1 11 12 if __name__ == '__main__': 13 print(num())
输出结果: