Hellnar、単純な辞書を使用して、文字列内の出現回数を数えることができます。アルゴリズムはカウントアルゴリズムです。例を次に示します。
"""
The counting algorithm is used to count the occurences of a character
in a string. This allows you to compare anagrams and strings themselves.
ex. animal, lamina a=2,n=1,i=1,m=1
"""
def count_occurences(str):
occurences = {}
for char in str:
if char in occurences:
occurences[char] = occurences[char] + 1
else:
occurences[char] = 1
return occurences
def is_matched(s1,s2):
matched = True
s1_count_table = count_occurences(s1)
for char in s2:
if char in s1_count_table and s1_count_table[char]>0:
s1_count_table[char] -= 1
else:
matched = False
break
return matched
#counting.is_matched("animal","laminar")
この例では、文字列が一致した場合にTrueまたはFalseを返します。このアルゴリズムは、文字が文字列に現れる回数をカウントすることを覚えておいてください。これはアナグラムに適しています。