我對編程很陌生,所以我希望你能幫助我。
我想檢查輸入字串是否是回文。回文檢查器不區分大小寫。
這是我到目前為止得到的:
# input word
word = input("Enter a word: ")
# make it case-INsensitive
word = word.lower()
# we also need the length of word to iterate over its range
length_word = int(len(word))
### use a for-loop
for letter in range(len(word)):
if word[-length_word] == word[-1]:
print(word, "is a palindrome.")
# if it doesn't match, its not a palindrome, print message
else:
print(word, "is not a palindrome.")
困擾我的是它列印出“是回文”這個短語。每次。我該如何解決它,以便如果單詞是回文,它只會列印一次?
非常感謝您!
uj5u.com熱心網友回復:
您只需要檢查單詞是否相反:
# input word
word = input("Enter a word: ")
# make it case-INsensitive
word = word.lower()
# check word against it's reverse
if word == word[::-1]:
print(word, "is a palindrome")
else:
print(word, "is not a palindrome")
uj5u.com熱心網友回復:
執行此操作的經典方法是將您的字串與同一字串的反轉(反轉)表示進行比較。您可以使用回圈來瀏覽字串。
這里有 3 種可能的方法來實作這一點。請注意,切片反向方法明顯快于其他任何一種策略。
from timeit import timeit
def ispalindrome_v1(s):
return s == s[::-1]
def ispalindrome_v2(s):
for i in range(len(s)//2):
if s[i] != s[-(i 1)]:
return False
return True
def ispalindrome_v3(s):
for c1, c2 in zip(s, reversed(s)):
if c1 != c2:
return False
return True
S = 'aabbcdcbbaa'
for func in ispalindrome_v1, ispalindrome_v2, ispalindrome_v3:
print(func.__name__, timeit(lambda: func(S)))
輸出:
ispalindrome_v1 0.18437389799873927
ispalindrome_v2 0.6897212660005607
ispalindrome_v3 0.7656042110011185
uj5u.com熱心網友回復:
我能想到的最好方法是 ScottC,但我會努力修復你自己的代碼:
您的主要錯誤是您只比較單詞的第一個和最后一個字母。您可以使用以下方法修復它:
if word[index] == word[-1-index]: # I replaced "letter" with "index" (see Thierry's comment)
第二個是結論是為回圈中的每個段落撰寫的,而不是在結尾處。解決此問題的一種方法(在許多其他方法中)是添加正確匹配的計數器,并測驗它是否適合代碼末尾的單詞長度。
# input word
word = input("Enter a word: ")
# make it case-INsensitive
word = word.lower()
# we also need the length of word to iterate over its range
length_word = len(word)
### use a for-loop
correct_matches = 0
for index in range(len(word)):
if word[index] == word[-1-index]:
correct_matches = 1
if correct_matches == length_word:
print(word, "is a palindrome.")
else:
print(word, "is not a palindrome.")
請注意,僅在單詞的前半部分回圈會更快。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/523800.html
上一篇:根據元素的長度向元素添加類
下一篇:從字串中反轉奇數長度的單詞
