回數是指從左向右讀和從右向左讀都是一樣的數,例如12321,909。請利用filter()篩選出回數

思路分析:

1、當數長度爲1表示爲10以內的數,此類數均屬於回數,所以均返回True

2、當數長度大於1,此時需分長度%2是否爲0,,如87與121不同處理,主要是截取數長度的後一半值與前一半值進行對比

3、最後通過filter過濾函數得到符合函數要求的列表值

def is_palindrome(num):
        if isinstance(num,int):
            listTmp=list(str(num))
            if len(listTmp)>=2:
                l=int(len(listTmp)/2)
                s1=listTmp[:l]
                if len(listTmp) % 2 == 0:
                    s2=listTmp[l:]
                else:
                    s2 = listTmp[l+1:]
                return s1==s2
            elif len(listTmp)==1:
                return True

# 測試:
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('測試失敗!')

1~1000: [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]
測試成功!

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章