Mason Desconi
Mason Desconi

Reputation: 27

Creating an anagram function

Been trying to figure this out for two hours or so, can't seem to figure out how to create an anagram function without using sorted(). Trying to figure it out without using splice, .find(), .count(), .replace(), and sorted(). Currently what I have which works:

def anagram(anag1, anag2):
    if (sorted(anag1) == sorted(anag2)):
        return True
    else:
        return False

If anybody has a way to do it without sorted that would be great.

Upvotes: 1

Views: 339

Answers (5)

U13-Forward
U13-Forward

Reputation: 71560

Try using all with a generator inside checking equality:

def anagram(anag1, anag2):
    if all(len([i for a in anag1 if a == i]) == len([i for b in anag2 if b == i]) for x in zip(anag1,anag2) for i in x):
        return True
    else:
        return False
print(anagram('car','arc'))

Output:

True

Upvotes: 0

benvc
benvc

Reputation: 15120

I like the sorted approach in your question as well as the collections.Counter approach better, but if you are just looking for alternatives you could use re.findall to determine whether each character in the first word occurs with the same frequency in the second word.

For example:

import re

def is_anagram(a, b):    
    return all(re.findall(c, a) == re.findall(c, b) for c in a)

print(is_anagram('cinema', 'iceman'))
#True

Upvotes: 0

Multihunter
Multihunter

Reputation: 5918

I assume you want to see a solution without any fancy collections or functions. Just primitive data types, loops and conditions. So, how about...

def count(word):
  map = {}
  for e in word:
    if e not in map:
      map[e] = 0
    map[e] += 1
  return map

def anagram(a, b):
  c1 = count(a)
  c2 = count(b)
  return all(c1[k] == c2[k] for k in c1)

Make a dictionary that lists the number of each element, then compares that there's the same number in both.

Upvotes: 0

Devendra
Devendra

Reputation: 1

using counter make dictionary of each input string after that we can compare those dictionaries if there is no any difference, it's anagram otherwise not.

from collections import Counter

def anagram(ang1,ang2):

    count_list1 = Counter(ang1)
    count_dict1 = dict(count_list1)

    count_list2 = Counter(ang2)
    count_dict2 = dict(count_list2)

    dict_compare_length = len(count_dict1.items() - count_dict2.items())

    if dict_compare_length==0:
        return True
    else:
        return False

print(anagram('listen','silen'))

Upvotes: 0

DirtyBit
DirtyBit

Reputation: 16772

Using Counter:

from collections import Counter

def anagram(str_1, str_2):
   return Counter(str_1) == Counter(str_2)

Upvotes: 2

Related Questions