Skip to content
51 changes: 51 additions & 0 deletions maths/leonardo_numbers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
"""
Leonardo numbers are a sequence of numbers given by the recurrence:
L(n) = L(n-1) + L(n-2) + 1
with initial values L(0) = 1 and L(1) = 1.

Reference: https://en.wikipedia.org/wiki/Leonardo_number
"""


def leonardo_numbers(n: int) -> int:

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please provide descriptive name for the parameter: n

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please provide descriptive name for the parameter: n

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please provide descriptive name for the parameter: n

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please provide descriptive name for the parameter: n

"""
Return the n-th Leonardo number.

>>> leonardo_numbers(0)
1
>>> leonardo_numbers(1)
1
>>> leonardo_numbers(2)
3
>>> leonardo_numbers(3)
5
>>> leonardo_numbers(4)
9
>>> leonardo_numbers(20)
21891
>>> leonardo_numbers(-1)
Traceback (most recent call last):
...
ValueError: n must be a non-negative integer
>>> leonardo_numbers(1.5)
Traceback (most recent call last):
...
ValueError: n must be a non-negative integer
"""
if not isinstance(n, int) or n < 0:
raise ValueError("n must be a non-negative integer")

if n == 0 or n == 1:

Check failure on line 38 in maths/leonardo_numbers.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (PLR1714)

maths/leonardo_numbers.py:38:8: PLR1714 Consider merging multiple comparisons: `n in {0, 1}`.
return 1

previous, current = 1, 1
for _ in range(n - 1):
previous, current = current, previous + current + 1

return current


if __name__ == "__main__":
import doctest

doctest.testmod()

Check failure on line 51 in maths/leonardo_numbers.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W292)

maths/leonardo_numbers.py:51:22: W292 No newline at end of file
Loading