Discuss / Python / 能直接用数据类型自带的运算最好

能直接用数据类型自带的运算最好

Topic source

alienation

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

刚开始想用reverse方法,但是发现是inplace的,这样无法通过比较来产生布尔值,干脆用切片直接倒叙好了

def is_palindrome(n):

    L = [i for i in str(n)]

    return L == L[::-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('测试失败!')

alienation

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

def is_palindrome(n):

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

原来可以直接对字符串切片啊

不器

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

帅哥,可以留个联系方式吗,哈哈哈

爱绛仙歌

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

太强了,简洁明了,参拜大佬

Terser

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

厉害,我还在一个个比较。没想到切片的第三个参数可以这样用!

大受震惊!

Wuli_杰杰

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

str(n) == str(n)[::-1] 这样的也是 123 == 321 不能判断吧


  • 1

Reply