From 3a4cc7e31084e15cf2cce24038957c686d41a1b3 Mon Sep 17 00:00:00 2001 From: Shriyans Gandhi <41372639+shri30yans@users.noreply.github.com> Date: Fri, 29 Oct 2021 13:09:32 +0530 Subject: [PATCH] Hexagonal number sequence (#5640) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Hexagonal number sequence A hexagonal number sequence is a sequence of figurate numbers where the nth hexagonal number hₙ is the number of distinct dots in a pattern of dots consisting of the outlines of regular hexagons with sides up to n dots, when the hexagons are overlaid so that they share one vertex. This program returns the hexagonal number sequence of n length. * Update hexagonalnumbers.py * Update hexagonalnumbers.py * Update hexagonalnumbers.py * Update hexagonalnumbers.py * Update and rename hexagonalnumbers.py to hexagonal_numbers.py * Length must be a positive integer Co-authored-by: Christian Clauss --- maths/series/hexagonal_numbers.py | 42 +++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 maths/series/hexagonal_numbers.py diff --git a/maths/series/hexagonal_numbers.py b/maths/series/hexagonal_numbers.py new file mode 100644 index 000000000..582b1989b --- /dev/null +++ b/maths/series/hexagonal_numbers.py @@ -0,0 +1,42 @@ +""" +A hexagonal number sequence is a sequence of figurate numbers +where the nth hexagonal number hₙ is the number of distinct dots +in a pattern of dots consisting of the outlines of regular +hexagons with sides up to n dots, when the hexagons are overlaid +so that they share one vertex. + + Calculates the hexagonal numbers sequence with a formula + hₙ = n(2n-1) + where: + hₙ --> is nth element of the sequence + n --> is the number of element in the sequence + reference-->"Hexagonal number" Wikipedia + +""" + + +def hexagonal_numbers(length: int) -> list[int]: + """ + :param len: max number of elements + :type len: int + :return: Hexagonal numbers as a list + + Tests: + >>> hexagonal_numbers(10) + [0, 1, 6, 15, 28, 45, 66, 91, 120, 153] + >>> hexagonal_numbers(5) + [0, 1, 6, 15, 28] + >>> hexagonal_numbers(0) + Traceback (most recent call last): + ... + ValueError: Length must be a positive integer. + """ + + if length <= 0 or not isinstance(length, int): + raise ValueError("Length must be a positive integer.") + return [n * (2 * n - 1) for n in range(length)] + + +if __name__ == "__main__": + print(hexagonal_numbers(length=5)) + print(hexagonal_numbers(length=10))