0
点赞
收藏
分享

微信扫一扫

【廖雪峰python教程filter练习题】回数是指从左向右读和从右向左读都是一样的数,例如12321,909。请利用filter()筛选出回数


题目链接

​​https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001431821084171d2e0f22e7cc24305ae03aa0214d0ef29000​​

正确实践

def is_palindrome(n):
return str(n)==str(n)[::-1]

output = filter(is_palindrome, range(1, 1000))
print(list(output))

解读

回文正序和逆序是相同的 。
str(n)必须要有
改成n == n[::-1]后报错如下:
return n==n[::-1]
TypeError: 'int' object is not subscriptable
str字符串有可以切片操作,而int不行


正确实践2

def is_palindrome(n):
s=str(n)
if len(s)==1:
return True
else:
lst=[c for c in s]
new_lst=[]
for x in range(len(lst)):
new_lst.append(lst[len(lst)-x-1])
if (''.join(new_lst))==s:
return True
else:
return False

output = filter(is_palindrome, range(1, 1000))
print(list(output))

解析

1、     .join() 把列表变成字符串
  2、 split() 把字符串转换成列表
s=str(n)这一步后len(s)这一步才正确


(完)



举报

相关推荐

0 条评论