Skip to content

Commit

Permalink
Add hailstone algorithm (keon#434)
Browse files Browse the repository at this point in the history
* Add hailstone algorithm in maths

* Add hailstone in README file

* Change type terms to int

* Add hailstone test
  • Loading branch information
jessicapaz authored and keon committed Oct 30, 2018
1 parent 996de27 commit 81d0e4d
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 1 deletion.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
13 changes: 13 additions & 0 deletions algorithms/maths/hailstone.py
Original file line number Diff line number Diff line change
@@ -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
15 changes: 14 additions & 1 deletion tests/test_maths.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@
pythagoras,
is_prime,
encrypt, decrypt,
combination, combination_memo
combination, combination_memo,
hailstone,
)

import unittest
Expand Down Expand Up @@ -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()

0 comments on commit 81d0e4d

Please sign in to comment.