我有这段代码:
def reverse (word):
newword = ''
letterflag = -1
for numletter in word:
newword += word[letterflag]
letterflag-=1
s=newword
s.upper()
return newword
def isPalindrome(word, ignorecase=False):
"""
>>> type(isPalindrome("bob"))
<type 'bool'>
>>> isPalindrome("abc")
False
>>> isPalindrome("bob")
True
>>> isPalindrome("a man a plan a canal, panama")
True
>>> isPalindrome("A man a plan a canal, Panama")
False
>>> isPalindrome("A man a plan a canal, Panama", ignorecase=True)
True
"""
word = str (word)
newword = reverse(word)
if word == newword:
return True
else:
return False
我希望当我输入Bob以返回true而不是因为大写字母B(python语言)而错误
答案 0 :(得分:0)
只需将输入设置为小写,就可以完全避免这个问题。
word = str(word)
word = word.lower()
word = word.replace(',', '') # removes any commas from the string
newword = word[::-1] # reverse string
if word == newword:
return True
else:
return False
答案 1 :(得分:0)
了解这个答案的最佳方法是在Python控制台中尝试各个部分。
要修复你的反向(),请执行以下操作:
def reverse (word):
newword = ''
letterflag = -1
for numletter in word:
newword += word[letterflag]
letterflag-=1
return newword
注意我也取出了.upper()部分,因为它们无效并且反转不是正确的地方,因为你无法将反转的大写单词与原始单词进行比较。 s.upper()
也不像您认为的那样有效。它返回s
的大写副本而不修改s
。您只需return newword.upper()
即可使其正常工作。
此外,不需要字母标记,您可以这样做:
def reverse (word):
newword = ''
for letter in word:
newword = letter + newword #adds each new letter to beginning
return newword
然而,执行反向功能的最简单方法是:
def reverse (word):
return word[::-1]
你的isPalendrome需要基本上起作用:
def isPalindrome(word, ignorecase=False):
word = word.replace(',', '').replace(' ', '') #removes ,'s and spaces
if ignorecase:
return word.lower() == reverse(word).lower()
else:
return word == reverse(word)
这是一个更高级的解决方案,它将忽略任何不具有忽略大小写选项的字母。这个版本需要反向。
def isPalindrome(word, ignorecase=False):
abcs = 'abcdefghijklmnopqrstuvwxyz'
word = [c for c in word.lower()*ignorecase or word if c in abcs]
return word == word[::-1] #no need for reverse
答案 2 :(得分:0)
如果您希望选项区分大小写,或者选项不区分大小写,请在isPalindrome()函数中添加IF语句:
if ignorecase == True:
word = word.lower()
完成后应该如下所示:
import string
def reverse (word):
newword = ''
letterflag = -1
for numletter in word:
newword += word[letterflag]
letterflag-=1
s=newword
s.upper()
return newword
def isPalindrome(word, ignorecase=False):
"""
>>> type(isPalindrome("bob"))
<type 'bool'>
>>> isPalindrome("abc")
False
>>> isPalindrome("bob")
True
>>> isPalindrome("a man a plan a canal, panama")
True
>>> isPalindrome("A man a plan a canal, Panama")
False
>>> isPalindrome("A man a plan a canal, Panama", ignorecase=True)
True
"""
if ignorecase == True:
word = word.lower()
word = word.replace(',', '')
word = word.replace(' ', '')
newword = reverse(word)
if word == newword:
return True
else:
return False
该代码给了我以下反馈:
isPalindrome('Bob', ignorecase=True)
Out[34]: True
isPalindrome('Bob')
Out[35]: False