Exercism v3 launches on Sept 1st 2021. Learn more! ๐Ÿš€๐Ÿš€๐Ÿš€
Avatar of ekingery

ekingery's solution

to Anagram in the Python Track

Published at Jul 13 2018 · 0 comments
Test suite


This solution was written on an old version of Exercism. The tests below might not correspond to the solution code, and the exercise may have changed since this code was written.

Given a word and a list of possible anagrams, select the correct sublist.

Given "listen" and a list of candidates like "enlists" "google" "inlets" "banana" the program should return a list containing "inlets".

Exception messages

Sometimes it is necessary to raise an exception. When you do this, you should include a meaningful error message to indicate what the source of the error is. This makes your code more readable and helps significantly with debugging. Not every exercise will require you to raise an exception, but for those that do, the tests will only pass if you include a message.

To raise a message with an exception, just write it as an argument to the exception type. For example, instead of raise Exception, you should write:

raise Exception("Meaningful message indicating the source of the error")

Running the tests

To run the tests, run the appropriate command below (why they are different):

  • Python 2.7: py.test anagram_test.py
  • Python 3.4+: pytest anagram_test.py

Alternatively, you can tell Python to run the pytest module (allowing the same command to be used regardless of Python version): python -m pytest anagram_test.py

Common pytest options

  • -v : enable verbose output
  • -x : stop running tests on first failure
  • --ff : run failures from previous test before running other test cases

For other options, see python -m pytest -h

Submitting Exercises

Note that, when trying to submit an exercise, make sure the solution is in the $EXERCISM_WORKSPACE/python/anagram directory.

You can find your Exercism workspace by running exercism debug and looking for the line that starts with Workspace.

For more detailed information about running tests, code style and linting, please see the help page.


Inspired by the Extreme Startup game https://github.com/rchatley/extreme_startup

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.


import unittest

from anagram import detect_anagrams

# Tests adapted from `problem-specifications//canonical-data.json` @ v1.2.0

class AnagramTest(unittest.TestCase):
    def test_no_matches(self):
        candidates = ["hello", "world", "zombies", "pants"]
        self.assertEqual(detect_anagrams("diaper", candidates), [])

    def test_detects_two_anagrams(self):
        candidates = ["stream", "pigeon", "maters"]
            detect_anagrams("master", candidates), ["stream", "maters"])

    def test_does_not_detect_anagram_subsets(self):
        self.assertEqual(detect_anagrams("good", ["dog", "goody"]), [])

    def test_detects_anagram(self):
        candidates = ["enlists", "google", "inlets", "banana"]
        self.assertEqual(detect_anagrams("listen", candidates), ["inlets"])

    def test_detects_three_anagrams(self):
        candidates = [
            "gallery", "ballerina", "regally", "clergy", "largely", "leading"
            detect_anagrams("allergy", candidates),
            ["gallery", "regally", "largely"])

    def test_does_not_detect_non_anagrams_with_identical_checksum(self):
        self.assertEqual(detect_anagrams("mass", ["last"]), [])

    def test_detects_anagrams_case_insensitively(self):
        candidates = ["cashregister", "Carthorse", "radishes"]
            detect_anagrams("Orchestra", candidates), ["Carthorse"])

    def test_detects_anagrams_using_case_insensitive_subject(self):
        candidates = ["cashregister", "carthorse", "radishes"]
            detect_anagrams("Orchestra", candidates), ["carthorse"])

    def test_detects_anagrams_using_case_insensitive_possible_matches(self):
        candidates = ["cashregister", "Carthorse", "radishes"]
            detect_anagrams("orchestra", candidates), ["Carthorse"])

    def test_does_not_detect_a_anagram_if_the_original_word_is_repeated(self):
        self.assertEqual(detect_anagrams("go", ["go Go GO"]), [])

    def test_anagrams_must_use_all_letters_exactly_once(self):
        self.assertEqual(detect_anagrams("tapper", ["patter"]), [])

    def test_capital_word_is_not_own_anagram(self):
        self.assertEqual(detect_anagrams("BANANA", ["Banana"]), [])

if __name__ == '__main__':
# pseudocode
# break needle into a hash, keyed by letters with values = # of appearances
# break each item of haystack into a dictionary, compare to needle

def detect_anagrams(needle, haystack):
    needle = needle.lower()
    needle_hash = hashify(needle)
    anagrams = [hay for hay in haystack
                if needle != hay.lower()
                and hashify(hay.lower()) == needle_hash]
    return anagrams

def hashify(word):
    hashword = {}
    for char in word:
        if char in hashword:
            hashword[char] += 1
            hashword[char] = 1
    return hashword

What can you learn from this solution?

A huge amount can be learned from reading other peopleโ€™s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?