Python实现寻找回文数字过程解析
作者:Johnthegreat 时间:2022-06-21 10:48:04
回文数字是很有意思的数字,不管从最高位开始念,还是从个位开始念,最终结果都一样,有一种对称美。
下面是回文数字的函数判断方式:
def is_palindrome(n):
str_num = str(n)
len_num = len(str_num)
if len_num <= 2 and str_num[0] == str_num[-1]:
return True
else:
half_len = round(len_num/2)
for i in range(half_len):
if not str_num[i] == str_num[-(i+1)]:
return False
return True
下面我们举个栗子,看3000以内有哪些回文数,以及有多少个这样的数字:
result = list(filter(is_palindrome, range(0, 3000)))
print(result, '\n', len(result))
输出如下:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191, 202, 212, 222, 232, 242, 252, 262, 272, 282, 292, 303, 313, 323, 333, 343, 353, 363, 373, 383, 393, 404, 414, 424, 434, 444, 454, 464, 474, 484, 494, 505, 515, 525, 535, 545, 555, 565, 575, 585, 595, 606, 616, 626, 636, 646, 656, 666, 676, 686, 696, 707, 717, 727, 737, 747, 757, 767, 777, 787, 797, 808, 818, 828, 838, 848, 858, 868, 878, 888, 898, 909, 919, 929, 939, 949, 959, 969, 979, 989, 999, 1001, 1111, 1221, 1331, 1441, 1551, 1661, 1771, 1881, 1991, 2002, 2112, 2222, 2332, 2442, 2552, 2662, 2772, 2882, 2992]
129
可以看到3000以内的自然数中,有129个回文数。
来源:https://www.cnblogs.com/johnthegreat/p/12872912.html
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python pandas时序处理相关功能详解
优雅地扩大链接响应区域
![](https://img.aspxhome.com/file/UploadPic/20109/25/2010-09-24_2300081-86s.png)
加密SQL Anywhere 提升政府行业数据安全
详解Python+Selenium+ChromeDriver的配置和问题解决
![](https://img.aspxhome.com/file/2023/5/86405_0s.png)
深入理解Python爬虫代理池服务
![](https://img.aspxhome.com/file/2023/9/100819_0s.png)
Python实现计算文件夹下.h和.cpp文件的总行数
pytest使用parametrize将参数化变量传递到fixture
利用Python yagmail三行代码实现发送邮件
![](https://img.aspxhome.com/file/2023/7/99677_0s.png)
Python中字典和JSON互转操作实例
七个生态系统核心库[python自学收藏]
![](https://img.aspxhome.com/file/2023/9/101699_0s.jpg)
Django中Forms的使用代码解析
![](https://img.aspxhome.com/file/2023/9/84079_0s.png)
重新编译PLSQL中的无效对象或者指定的对象 的方法
python之信息加密题目详解
Python使用扩展库pywin32实现批量文档打印实例
OpenCV学习之图像加噪与滤波的实现详解
![](https://img.aspxhome.com/file/2023/0/105040_0s.png)
Asp 返回引用类型函数代码
Python 控制终端输出文字的实例
python爬虫爬取股票的北上资金持仓数据
![](https://img.aspxhome.com/file/2023/4/82524_0s.webp)