判斷一條字串是否形成迴文
阿新 • • 發佈:2018-12-01
要想檢查文字是否屬於迴文需要忽略其中的標點、空格與大小寫。例如,“Rise to vote, sir.”是一段迴文文字,但是我們現有的程式不會這麼認為。你可以改進上面的程式以使它能夠識別這段迴文嗎?(《python簡明教程》裡“輸入與輸出”章節的作業練習)。
主要思路:
1.把字串全部轉成小寫或全部轉成大寫,可以用到str.lower()和str.upper()。
2.識別空格和標點符號,若有就跳過或者刪除。使用一個元組(你可以在這裡找到一份列出所有標點符號的列表)來儲存所有需要禁用的字元,然後使用成員資格測試來確定一個字元 是否應該被移除,即 forbidden = ('!' , '?' , '.', ' ...')。可以用到 str.remove(obj)。
s2=list(s1) forbidden = ('!' ,'?' , '.' , '...' ,',' ,) for i in s2: if i in forbidden or i ==' ': s2.remove(i)
3.判斷是否為迴文。字串倒置回來的字串等於原有的字串。
字串:
def fanzhuan(text):
return text[::-1]
def is_fanzhuan(text):
return text == fanzhuan(text)
列表:
str3=str2.copy() str2.reverse() #str.reverse()是變更str2,會改變str2的值,不返回一個新的值。==也只是令變數指向該物件。所以前面用#s.copy()創造出新的物件。
參考程式碼:
def chuli_str(text):
s1=text.lower()
s2=list(s1)
forbidden = ('!' ,'?','.', '...',',',)
for i in s2:
if i in forbidden or i ==' ':
s2.remove(i)
return s2
def fanzhuan(text):
return text[::-1]
def is_fanzhuan(text):
return text == fanzhuan(text)
str1 = input("please inter your want to input:")
str2=chuli_str(str1)
#第一個方法(用函式實現)
if is_fanzhuan(str2):
print("right")
else:
print("wrong")
"""
#第二個方法
str3=str2.copy()
str2.reverse()
if str3==str2:
print("right")
else:
print("wrong")
"""
不足和解決方法:
1.第一個想法:把所有標點符號全部轉化成空格,然後化為字串。
錯誤參考程式碼:
for i in str1:
for i in forbidden:
str1.replace(i ,' ')
不足:
i 執行一次,都會把之前的值覆蓋,得出的結果,只有對最後一個值起作用。而且字串是固定不變,列表是可變的,可以更改內容的。
解決方法:暫時還沒解決。
2.第二個想法:首先申請一個空的字串,遇到不是標點符號或者空格,就往字串裡新增。
錯誤參考程式碼:
a=""
for i in str1:
if i not in forbidden and i !=' ':
a+=i
不足:i 執行一次,都會把之前的值覆蓋,得出的結果,只有對最後一個值起作用。且用不了a.append()和a.extend()(用於列表之類可變)。
解決方法:用列表來實現
a=[]
for i in s1:
if i not in forbidden and i !=' ':
a.extend(i)
總結:字串是不可變的,無法改變內容;列表是可變的,可以改變內容。