回数定义:从左向右读和从右向左读都是一样的数,例如:12321,909
#方法一
def is_palindrome(n):
num_str = str(n)
num_len = len(num_str)
if num_len <= 1:
return True
start = 0
while start < int(num_len / 2):
if num_str[start] != num_str[-(start+1)]:
return False
start += 1
return True
#方法二:
def is_palindrome2(n):
num_str = str(n)
#双斜杠"//"表示的是对数据取整
for i in range((len(s)+1) // 2):
if s[i] != s[-(i+1)]:
return False
return True
#方法三: 使用字符串转list,list反转后在转字符串
def is_palindrome3(n):
num_str = str(n)
num_list = list(num_str)
num_list.reverse()
return num_str == ''.join(num_list)
#方法四: 使用切片反转字符串
def is_palindrome4(n):
return str(n) == str(n)[::-1]
print(list(filter(is_palindrome, range(1,110))))
print(list(filter(is_palindrome2, range(1,110))))
print(list(filter(is_palindrome3, range(1,110))))
print(list(filter(is_palindrome4, range(1,110))))
#结果:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101]
网友评论