简体   繁体   English

递归和列表理解?

[英]Recursion and list comprehension?

is "lst[1:-1]" any different from "lst[1:]"? “lst[1:-1]”与“lst[1:]”有什么不同吗? in this situation:在这个情况下:

def is_pal(string):
    if len(string) < 2:
        return True
    elif string[0] != string[-1]:
        return False
    else:
        return is_pal(string[1:-1]) 

The code is Checking whether string is palindrome.代码是检查字符串是否为回文。

-1 is exclusive, meaning [1:-1] will return the whole string except for the first (0) and the last characters. -1 是独占的,这意味着 [1:-1] 将返回除第一个 (0) 和最后一个字符之外的整个字符串。

BTW you can just reverse the text and check it that way:顺便说一句,您可以反转文本并以这种方式检查:

def is_pal(string):
    return string[::-1] == string

consider a string,考虑一个字符串,

s = "abcdef"

s[1:] = "bcdef"

s[1:-1] = "bcde"

To check whether the given string is palindrome or not, just compare the given string s with string s[::-1] .要检查给定字符串是否为回文,只需将给定字符串s与字符串s[::-1]进行比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM