Discuss / Python / homework

homework

Topic source

gitKong

#1 Created at ... [Delete] [Delete and Lock User]
复杂版。。。

def is_palindrome(n):
    if not isinstance(n, int):
        raise TypeError('Error Type Compare')
    L = list(map(int, str(n)))
    index = 0
    flag = False
    endIndex = len(L) / 2 - 1 if len(L) % 2 == 0 else (len(L) - 1) / 2 if len(L) <= 1 else (len(L) - 1) / 2 - 1
    while index <= endIndex and L[index:1] == (L[-(index + 1):-index] if index > 0 else L[-(index + 1):]):
        if index == endIndex:
            flag = True
            break
        index = index + 1
    return flag

忘记有[::-1]了,所以其实可以直接拿到反转后的字符串进行判断

gitKong

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

为了避免误导,map是我故意用得哈~实际上不需要,直接操作str即可

这段代码我试了一下, 没办法衍生到更大的数,比如,一万, 十万。   看来还是 [::-1]简便。


  • 1

Reply