From 81d0e4d81ec55a0c9f5d5f9f7dcefe27e4f9db53 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9ssica=20Paz?= Date: Tue, 30 Oct 2018 04:43:04 -0300 Subject: [PATCH] Add hailstone algorithm (#434) * Add hailstone algorithm in maths * Add hailstone in README file * Change type terms to int * Add hailstone test --- README.md | 1 + algorithms/maths/hailstone.py | 13 +++++++++++++ tests/test_maths.py | 15 ++++++++++++++- 3 files changed, 28 insertions(+), 1 deletion(-) create mode 100644 algorithms/maths/hailstone.py diff --git a/README.md b/README.md index aecd53b6d..4443884e4 100644 --- a/README.md +++ b/README.md @@ -203,6 +203,7 @@ If you want to uninstall algorithms, it is as simple as: - [rsa](algorithms/maths/rsa.py) - [sqrt_precision_factor](algorithms/maths/sqrt_precision_factor.py) - [summing_digits](algorithms/maths/summing_digits.py) + - [hailstone](algorithms/maths/hailstone.py) - [matrix](algorithms/matrix) - [sudoku_validator](algorithms/matrix/sudoku_validator.py) - [bomb_enemy](algorithms/matrix/bomb_enemy.py) diff --git a/algorithms/maths/hailstone.py b/algorithms/maths/hailstone.py new file mode 100644 index 000000000..22321232b --- /dev/null +++ b/algorithms/maths/hailstone.py @@ -0,0 +1,13 @@ +def hailstone(n): + """Return the 'hailstone sequence' from n to 1 + n: The starting point of the hailstone sequence + """ + + sequence = [n] + while n > 1: + if n%2 != 0: + n = 3*n + 1 + else: + n = int(n/2) + sequence.append(n) + return sequence \ No newline at end of file diff --git a/tests/test_maths.py b/tests/test_maths.py index 0777f9ab3..dd1d0e137 100644 --- a/tests/test_maths.py +++ b/tests/test_maths.py @@ -14,7 +14,8 @@ pythagoras, is_prime, encrypt, decrypt, - combination, combination_memo + combination, combination_memo, + hailstone, ) import unittest @@ -288,5 +289,17 @@ def test_factorial_recur(self): self.assertRaises(ValueError, factorial_recur, 42, -1) +class TestHailstone(unittest.TestCase): + """[summary] + Test for the file hailstone.py + + Arguments: + unittest {[type]} -- [description] + """ + def test_hailstone(self): + self.assertEqual([8, 4, 2, 1], hailstone.hailstone(8)) + self.assertEqual([10, 5, 16, 8, 4, 2, 1], hailstone.hailstone(10)) + + if __name__ == "__main__": unittest.main()