Home > Back-end >  return a dictionary with a number of instances for each character
return a dictionary with a number of instances for each character

Time:10-27

This function takes two character strings corresponding to two words and returns True if and only if one is anagram of the other, that is, if the words are constituted by the same letters, ignoring differences between uppercase and lowercase and the order between characters.

>>> eh_anagrama(’caso’, ’SaCo’)
True
>>> eh_anagrama(’caso’, ’casos’)
False

CodePudding user response:

Simple, but log-linear approach:

def eh_anagrama(s1, s2):
    return sorted(s1.lower()) == sorted(s2.lower())

Better linear approach, using collections.Counter:

from collections import Counter

def eh_anagrama(s1, s2):
    return Counter(s1.lower()) == Counter(s2.lower())

The benefits of this will probaby only be reaped for very long strings, as the sorting is heavily C-optimized.

CodePudding user response:

How about this with result and char counting in dict.

code

def anagram(s1, s2):
    ana = sorted(s1.lower()) == sorted(s2.lower())
    
    d1 = {}
    d2 = {}
    for x in set(s1):  # Get unique char
        d1.update({x: s1.count(x)})  # Count each char
    for x in set(s2):
        d2.update({x: s2.count(x)})

    return {'anagram': ana, s1: d1, s2: d2}


s1 = 'caso'
s2 = 'SaCo'
res1 = anagram(s1, s2)
print(res1)

s1 = 'caso'
s2 = 'casos'
res2 = anagram(s1, s2)
print(res2)

Output:

{'anagram': True, 'caso': {'o': 1, 's': 1, 'c': 1, 'a': 1}, 'SaCo': {'o': 1, 'C': 1, 'a': 1, 'S': 1}}
{'anagram': False, 'caso': {'o': 1, 's': 1, 'c': 1, 'a': 1}, 'casos': {'o': 1, 's': 2, 'c': 1, 'a': 1}}
  • Related