python算法:水仙花数
一,for循环:
1,功能:重复执行同一段代码
语法:
for index in range(n):
# 循环体代码
index : 用来依次接收可迭代对象中的元素的变量名
range()函数:负责返回整数序列
流程图:

2,应用
range可以同时指定start 和stop,用for遍历并打印
|
1
2
3
4
|
# 指定 start和stop# print的参数 end=" " 用来使打印不换行for num in range(3,9): print(num, end=" ") |
运行结果:
3 4 5 6 7 8
说明:刘宏缔的架构森林—专注it技术的博客,
网址:https://imgtouch.com
本文: https://blog.imgtouch.com/index.php/2024/03/12/python-suan-fa-shui-xian-hua-shu/
代码: https://github.com/liuhongdi/ 或 https://gitee.com/liuhongdi
说明:作者:刘宏缔 邮箱: 371125307@qq.com
二,什么是水仙花数?
1,如果一个三位数,它的各个位上的数字的立方和等于它本身,我们就称之为水仙花数
例子:371,
3^3 + 7^3 + 1^3 = 27+ 343 + 1 = 371
2,思路:
遍历从100到999之间的所有三位数,
得到各位上的数字,
判断是否其各位的立方求和后等于本身即可
三,编写代码打印水仙花数
1,通过计算得到各位上的数字
|
1
2
3
4
5
6
7
8
9
10
11
12
|
# for循环,遍历 100 到 999 之间的数字for num in range(100, 1000): hundreds = num // 100 # 获取百位上的数字 tens = (num // 10) % 10 # 获取十位上的数字 units = num % 10 # 获取个位上的数字 # 得到各位上数字的立方的和 sumRes = hundreds ** 3 + tens ** 3 + units ** 3 # 如果当前数字等于立方的和,则表示是水仙花数 if num == sumRes: print(num) # 输出水仙花数 |
运行结果:
153
370
371
407
2,通过转字符串得到各位上的数字
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
# for循环,遍历 100 到 999 之间的数字for num in range(100, 1000): s = str(num) # 得到数字的字符串形式 hundreds = int(s[0]) # 获取百位上的数字 tens = int(s[1]) # 获取十位上的数字 units = int(s[2]) # 获取个位上的数字 # 得到各位上数字的立方的和 sumRes = hundreds ** 3 + tens ** 3 + units ** 3 # 如果当前数字等于立方的和,则表示是水仙花数 if num == sumRes: print(num) # 输出水仙花数 |
运行结果:
153
370
371
407
3,3层循环得到各位上数字
|
1
2
3
4
5
6
7
8
9
10
|
import cProfile# for循环,遍历 100 到 999 之间的数字for hundred in range(1, 10): # 百位数字,[1,9] for ten in range(0, 10): # 十位数字,[0,9] for unit in range(0, 10): # 十位数字,[0,9] num = hundred*100 + ten * 10 + unit # 数字本身 # 得到各位上数字的立方的和 sumRes = hundred ** 3 + ten ** 3 + unit ** 3 # 立方和 if num == sumRes: print(num) # 输出水仙花数 |
运行结果:
153
370
371
407

浙公网安备 33010602011771号