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.3.tar.gz
(2.5 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.3.tar.gz.
File metadata
- Download URL: tailrec-0.1.3.tar.gz
- Upload date:
- Size: 2.5 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 |
8179ffd02e10ab2d1c9d4f964afcd7280362647a5472493990504cb350dfa42f
|
|
| MD5 |
7248cb1fa55a29024b88a8d8d2311a08
|
|
| BLAKE2b-256 |
621dc2af87229c2cf07069b6f8c921940139b9de21685d2c7c5bbad3b5d8db96
|
File details
Details for the file tailrec-0.1.3-py3-none-any.whl.
File metadata
- Download URL: tailrec-0.1.3-py3-none-any.whl
- Upload date:
- Size: 3.6 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 |
8ed7c6a65a440878ca4a9d3fe79a8946e2f0c7c1eab0b70c6c42c39ea84c41d8
|
|
| MD5 |
cb975ce5ac69550052c83cd805bb1e88
|
|
| BLAKE2b-256 |
fc3e53b4d834ef32eb03a45b7f519b75675483ed86c078550cf21a75ed633340
|