# -*- coding: utf-8 -*- def is_palindrome(n): d = str(n) # 将数字转化成字符串 s = len(d) # 获取字符串长度 if s == 1: # 一位数的话直接返回 return n for a in range(0, s//2): #通过字符串长度取整决定循环次数 if d[a] == d[-(a+1)]: return n # return str(n) == str(n)[::-1] # 其实代码只需要一句,字符串顺序和倒序全部相同 output = filter(is_palindrome, range(1, 1000)) print('1~1000的回数:', list(output)) if list(filter(is_palindrome, range(1, 200))) == [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]: print('测试成功!') else: print('测试失败!')
Python 回数
最新推荐文章于 2021-10-18 19:23:30 发布