Calculate the Hamming difference between two DNA strands.
A mutation is simply a mistake that occurs during the creation or copying of a nucleic acid, in particular DNA. Because nucleic acids are vital to cellular functions, mutations tend to cause a ripple effect throughout the cell. Although mutations are technically mistakes, a very rare mutation may equip the cell with a beneficial attribute. In fact, the macro effects of evolution are attributable by the accumulated result of beneficial microscopic mutations over many generations.
The simplest and most common type of nucleic acid mutation is a point mutation, which replaces one base with another at a single nucleotide.
By counting the number of differences between two homologous DNA strands taken from different genomes with a common ancestor, we get a measure of the minimum number of point mutations that could have occurred on the evolutionary path between the two strands.
This is called the 'Hamming distance'.
It is found by comparing two DNA strands and counting how many of the nucleotides are different from their equivalent in the other string.
GAGCCTACTAACGGGAT CATCGTAATGACGGCCT ^ ^ ^ ^ ^ ^^
The Hamming distance between these two DNA strands is 7.
The Hamming distance is only defined for sequences of equal length, so an attempt to calculate it between sequences of different lengths should not work. The general handling of this situation (e.g., raising an exception vs returning a special value) may differ between languages.
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")
To run the tests, run the appropriate command below (why they are different):
Alternatively, you can tell Python to run the pytest module (allowing the same command to be used regardless of Python version):
python -m pytest hamming_test.py
-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
Note that, when trying to submit an exercise, make sure the solution is in the
You can find your Exercism workspace by running
exercism debug and looking for the line that starts with
For more detailed information about running tests, code style and linting, please see the help page.
The Calculating Point Mutations problem at Rosalind http://rosalind.info/problems/hamm/
It's possible to submit an incomplete solution so you can see how others have completed the exercise.
import unittest import hamming # Tests adapted from `problem-specifications//canonical-data.json` @ v2.1.0 class HammingTest(unittest.TestCase): def test_empty_strands(self): self.assertEqual(hamming.distance("", ""), 0) def test_identical_strands(self): self.assertEqual(hamming.distance("A", "A"), 0) def test_long_identical_strands(self): self.assertEqual(hamming.distance("GGACTGA", "GGACTGA"), 0) def test_complete_distance_in_single_nucleotide_strands(self): self.assertEqual(hamming.distance("A", "G"), 1) def test_complete_distance_in_small_strands(self): self.assertEqual(hamming.distance("AG", "CT"), 2) def test_small_distance_in_small_strands(self): self.assertEqual(hamming.distance("AT", "CT"), 1) def test_small_distance(self): self.assertEqual(hamming.distance("GGACG", "GGTCG"), 1) def test_small_distance_in_long_strands(self): self.assertEqual(hamming.distance("ACCAGGG", "ACTATGG"), 2) def test_non_unique_character_in_first_strand(self): self.assertEqual(hamming.distance("AAG", "AAA"), 1) def test_non_unique_character_in_second_strand(self): self.assertEqual(hamming.distance("AAA", "AAG"), 1) def test_same_nucleotides_in_different_positions(self): self.assertEqual(hamming.distance("TAG", "GAT"), 2) def test_large_distance(self): self.assertEqual(hamming.distance("GATACA", "GCATAA"), 4) def test_large_distance_in_off_by_one_strand(self): self.assertEqual(hamming.distance("GGACGGATTCTG", "AGGACGGATTCT"), 9) def test_disallow_first_strand_longer(self): with self.assertRaisesWithMessage(ValueError): hamming.distance("AATG", "AAA") def test_disallow_second_strand_longer(self): with self.assertRaisesWithMessage(ValueError): hamming.distance("ATA", "AGTG") # Utility functions def setUp(self): try: self.assertRaisesRegex except AttributeError: self.assertRaisesRegex = self.assertRaisesRegexp def assertRaisesWithMessage(self, exception): return self.assertRaisesRegex(exception, r".+") if __name__ == '__main__': unittest.main()
VALID_DNA_BASES = ['A', 'T', 'G', 'C'] def distance(strand1, strand2): """Calculate the Hamming distance between two DNA strands.""" if len(strand1) != len(strand2): raise ValueError max_distance = len(strand1) final_distance = 0 for idx in range(0, max_distance): if strand1[idx] not in VALID_DNA_BASES: raise ValueError if strand2[idx] not in VALID_DNA_BASES: raise ValueError if strand1[idx] != strand2[idx]: final_distance = final_distance + 1 return final_distance
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.