Python で与えられた文が回文かどうかを確認します。
回文(かいぶん)とは、始めから(通常通り)読んだ場合と終わりから(通常と逆に)読んだ場合とで文字ないし音節の出現する順番が変わらず、なおかつ、言語としてある程度意味が通る文字列のことで、言葉遊びの一種である。英語では palindrome ([ˈpælɨndroʊm] パリンドローム)という。
出典: フリー百科事典『ウィキペディア(Wikipedia)』
句読点を取り除くため、string の maketrans か正規表現を使います。
あとは文字列を逆順にして比較するだけです。
import re
import string
def is_plindrome(text):
text = delete_punctuation(text).lower()
reversed_text = text[::-1]
return text == reversed_text
def delete_punctuation(text):
# # using string
# text = text.replace(' ', '')
# table = text.maketrans("", "", string.punctuation)
# text_del_punc = text.translate(table)
# using re
text = re.sub(r'[\W]', '', text)
text_del_punc = re.sub(r'\_', '', text)
return text_del_punc
re.sub(r'[\W]', '', s)
s = re.sub(r'\_', '', s)
if __name__ == '__main__':
str_1 = "A man, a plan, a canal - _Panama_"
str_2 = "A man, a plan, a canal - _Japan_"
# True
print(is_plindrome(str_1))
# False
print(is_plindrome(str_2))