Execute a tail recursive function iteratively
Project description
tailrec
Provides a decorator tailrec which executes a tail recursive function iteratively
Installation
pip install tailrec
Examples
from tailrec import tailrec
@tailrec
def factorial(n: int, accum: int = 1) -> int:
"""Calculates n!"""
if n == 0:
return accum
else:
return factorial(n - 1, accum * n)
@tailrec
def fibonacci(n: int, current: int = 0, next_: int = 1) -> int:
"""Returns the n-th number of the fibonacci sequence"""
if n == 0:
return current
else:
return fibonacci(n - 1, next_, current + next_)
print(factorial(5)) # 120
print(factorial(1_100)) # 5343708488092637703...
print(fibonacci(5)) # 8
print(fibonacci(2_000)) # 42246963333923...
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
tailrec-0.1.5.tar.gz
(3.0 kB
view details)
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file tailrec-0.1.5.tar.gz.
File metadata
- Download URL: tailrec-0.1.5.tar.gz
- Upload date:
- Size: 3.0 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/2.1.1 CPython/3.11.3 Windows/10
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
4ddcba1020c139d2cdd4815b794f2b6e0f2bd2675f67428b004058d61013dbb4
|
|
| MD5 |
d3e3552da9e88bff3490bb8ead644a10
|
|
| BLAKE2b-256 |
40f027147e965f8a2925db07db199ae522852ad4a93cec31309495680bce3e2f
|
File details
Details for the file tailrec-0.1.5-py3-none-any.whl.
File metadata
- Download URL: tailrec-0.1.5-py3-none-any.whl
- Upload date:
- Size: 4.3 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/2.1.1 CPython/3.11.3 Windows/10
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
e21508eafb3bf76ba711720b608fbf0079394b99b265d8b2a9df695bbbd221c3
|
|
| MD5 |
59f0b5d7caa20275db4d80fbda1201e6
|
|
| BLAKE2b-256 |
a1e8500bb1143a046bcbff232091b53a108efb63199c1f0a01eff8128ec653c0
|