Discuss / Python / 交作业,列表逆序排列

交作业,列表逆序排列

Topic source

孤月情风

#1 Created at ... [Delete] [Delete and Lock User]

列表逆序排列,如果相等,则为回数。

def is_palindrome(n):
    return list(str(n)) == list(reversed(list(str(n))))

>>> 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]

孤月情风

#2 Created at ... [Delete] [Delete and Lock User]

逆序的另一种写法:

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

>>> 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]

  • 1

Reply