Skip to content

Commit 81d0e4d

Browse files
jessicapazkeon
authored andcommitted
Add hailstone algorithm (keon#434)
* Add hailstone algorithm in maths * Add hailstone in README file * Change type terms to int * Add hailstone test
1 parent 996de27 commit 81d0e4d

File tree

3 files changed

+28
-1
lines changed

3 files changed

+28
-1
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -203,6 +203,7 @@ If you want to uninstall algorithms, it is as simple as:
203203
- [rsa](algorithms/maths/rsa.py)
204204
- [sqrt_precision_factor](algorithms/maths/sqrt_precision_factor.py)
205205
- [summing_digits](algorithms/maths/summing_digits.py)
206+
- [hailstone](algorithms/maths/hailstone.py)
206207
- [matrix](algorithms/matrix)
207208
- [sudoku_validator](algorithms/matrix/sudoku_validator.py)
208209
- [bomb_enemy](algorithms/matrix/bomb_enemy.py)

algorithms/maths/hailstone.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
def hailstone(n):
2+
"""Return the 'hailstone sequence' from n to 1
3+
n: The starting point of the hailstone sequence
4+
"""
5+
6+
sequence = [n]
7+
while n > 1:
8+
if n%2 != 0:
9+
n = 3*n + 1
10+
else:
11+
n = int(n/2)
12+
sequence.append(n)
13+
return sequence

tests/test_maths.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,8 @@
1414
pythagoras,
1515
is_prime,
1616
encrypt, decrypt,
17-
combination, combination_memo
17+
combination, combination_memo,
18+
hailstone,
1819
)
1920

2021
import unittest
@@ -288,5 +289,17 @@ def test_factorial_recur(self):
288289
self.assertRaises(ValueError, factorial_recur, 42, -1)
289290

290291

292+
class TestHailstone(unittest.TestCase):
293+
"""[summary]
294+
Test for the file hailstone.py
295+
296+
Arguments:
297+
unittest {[type]} -- [description]
298+
"""
299+
def test_hailstone(self):
300+
self.assertEqual([8, 4, 2, 1], hailstone.hailstone(8))
301+
self.assertEqual([10, 5, 16, 8, 4, 2, 1], hailstone.hailstone(10))
302+
303+
291304
if __name__ == "__main__":
292305
unittest.main()

0 commit comments

Comments
 (0)