Python で与えられた文がアナグラムかどうか確認します。
アナグラム(anagram)とは、言葉遊びの一つで、単語または文の中の文字をいくつか入れ替えることによって、全く別の意味にさせる遊びである。
出典: フリー百科事典『ウィキペディア(Wikipedia)』
回文と似ていますが、アナグラムでは文字をソートしなければならないので、\( O (N \log N) \) になります。
import re
def is_anagram(text1, text2):
text1 = delete_punctuation(text1)
text2 = delete_punctuation(text2)
if len(text1) != len(text2):
return False
# O (N log N)
text1 = sorted(text1)
text2 = sorted(text2)
return text1 == text2
def delete_punctuation(text):
text = re.sub(r'[\W]', '', text)
text_del_punc = re.sub(r'\_', '', text)
return text_del_punc.lower()
if __name__ == '__main__':
text1 = 'anagrams'
text2 = 'ARS MAGNA'
# True
print(is_anagram(text1, text2))
text1 = 'anagram'
text2 = 'ARS MAGNA'
# False
print(is_anagram(text1, text2))