测试列表或字符串是否是回文

我有一个最后的预告片,老师说他计划在问题清单中包括一个回文检查程序。基本上,我需要编写两个单独的函数,一个用于测试列表是否是回文(如果是,则返回True),另一个用于测试字符串。


到目前为止,这就是我所拥有的。似乎给我带来了麻烦:


def palindrome(s)

index = 0

index = True

     while index < len(s)        

        if n[index]==n[-1-index]

        index=1

        return True

     return False

我不太确定从那里去哪里。


慕的地8271018
浏览 185回答 2
2回答

三国纷争

对于列表或字符串:seq&nbsp;==&nbsp;seq[::-1]

慕盖茨4494581

这是您的功能,是幼稚的方式。适用于奇数和偶数回文,列表和字符串:def is_palindrome(s):&nbsp; &nbsp; return s == s[::-1]另一个问题是回文仅是奇数或偶数序列,还是两者都存在?我的意思是不仅应abccba和abcba匹配,或只是其中之一?如果您只想将奇数或偶数序列视为回文,则可以添加测试:def is_palindrome(s, t='both'):&nbsp; &nbsp; # only odd sequences can be palindromes&nbsp; &nbsp; if t=='odd':&nbsp; &nbsp; &nbsp; &nbsp; if len(s)%2 == 0:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return False&nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return s == s[::-1]&nbsp; &nbsp; # only even sequences can be palindromes&nbsp; &nbsp; elif t=='even':&nbsp; &nbsp; &nbsp; &nbsp; if len(s)%2:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return False&nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return s == s[::-1]&nbsp; &nbsp; # both even or odd sequences can be palindromes&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; return s == s[::-1]作为字符串,只有一个函数是字符列表。如果您的老师真的想要两个功能,您仍然可以使用别名:def is_list_palindrome(l, t='both'):&nbsp; &nbsp; return is_palindrome(l, t)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python