Back to home

Test fileAnagramsRunning tests
Python Anagrams main image

Python Anagrams

Test file

Create file anagrams_test.py:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 import unittest import anagrams class AnagramsTest(unittest.TestCase): def test_anagrams(self): assess = [ { "inputA": "toyko", "inputB": "kyoto", "expectation": True }, { "inputA": "toyko", "inputB": "kyotoooo", "expectation": False }, { "inputA": "t!!o.9 yko", "inputB": "kyoto", "expectation": True }, { "inputA": "racecar", "inputB": "carrace", "expectation": True }, { "inputA": "TOKYO", "inputB": "kyoto", "expectation": True } ] for test in assess: self.assertEqual(anagrams.isAnagram( test["inputA"], test["inputB"]), test["expectation"]) if __name__ == '__main__': unittest.main()

Anagrams

Create file anagrams.py.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 import re def isAnagram(strA, strB): reStrA = re.sub("[^a-zA-Z]", "", strA).strip().lower() reStrB = re.sub("[^a-zA-Z]", "", strB).strip().lower() print(reStrA) print(reStrB) dictA = {} for c in reStrA: if c in dictA.keys(): dictA[c] = dictA[c] + 1 else: dictA[c] = 1 dictB = {} for c in reStrB: if c in dictB.keys(): dictB[c] = dictB[c] + 1 else: dictB[c] = 1 if len(dictA) != len(dictB): return False for c in dictA: if dictB[c] == None: return False if dictA[c] != dictB[c]: return False return True

Running tests

Change into directory and run python3 -m pytest -v anagrams_test.py.

Dennis O'Keeffe

@dennisokeeffe92
  • Melbourne, Australia

Hi, I am a professional Software Engineer. Formerly of Culture Amp, UsabilityHub, Present Company and NightGuru.
I am currently working on workingoutloud.dev, Den Dribbles and LandPad .

Related articles


1,200+ PEOPLE ALREADY JOINED ❤️️

Get fresh posts + news direct to your inbox.

No spam. We only send you relevant content.