Skip to content

Commit 3a4cc7e

Browse files
shri30yanscclauss
andauthored
Hexagonal number sequence (#5640)
* 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 <[email protected]>
1 parent a281151 commit 3a4cc7e

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

maths/series/hexagonal_numbers.py

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
"""
2+
A hexagonal number sequence is a sequence of figurate numbers
3+
where the nth hexagonal number hₙ is the number of distinct dots
4+
in a pattern of dots consisting of the outlines of regular
5+
hexagons with sides up to n dots, when the hexagons are overlaid
6+
so that they share one vertex.
7+
8+
Calculates the hexagonal numbers sequence with a formula
9+
hₙ = n(2n-1)
10+
where:
11+
hₙ --> is nth element of the sequence
12+
n --> is the number of element in the sequence
13+
reference-->"Hexagonal number" Wikipedia
14+
<https://en.wikipedia.org/wiki/Hexagonal_number>
15+
"""
16+
17+
18+
def hexagonal_numbers(length: int) -> list[int]:
19+
"""
20+
:param len: max number of elements
21+
:type len: int
22+
:return: Hexagonal numbers as a list
23+
24+
Tests:
25+
>>> hexagonal_numbers(10)
26+
[0, 1, 6, 15, 28, 45, 66, 91, 120, 153]
27+
>>> hexagonal_numbers(5)
28+
[0, 1, 6, 15, 28]
29+
>>> hexagonal_numbers(0)
30+
Traceback (most recent call last):
31+
...
32+
ValueError: Length must be a positive integer.
33+
"""
34+
35+
if length <= 0 or not isinstance(length, int):
36+
raise ValueError("Length must be a positive integer.")
37+
return [n * (2 * n - 1) for n in range(length)]
38+
39+
40+
if __name__ == "__main__":
41+
print(hexagonal_numbers(length=5))
42+
print(hexagonal_numbers(length=10))

0 commit comments

Comments
 (0)