jabbalaci / SpeedTests

comparing the execution speeds of various programming languages
MIT License
84 stars 27 forks source link

Python with Numba #45

Closed smazurchuk closed 8 months ago

smazurchuk commented 8 months ago

Interesting repo! Thanks for sharing.

Would you be open to a python implementation that uses the numba library? It is a popular library for those doing computationally intensive tasks with python. Using it requires the cache variable to be a global and immutable (e.g., a numpy array). This implementation runs in 28s on my machine, and is only a minor modification of your python3.10

import numpy as np
from numba import njit, prange

N = 440_000_000
#N = 10_000_000

cache = np.array([0] + [i ** i for i in range(1, 9+1)])

@njit
def is_munchausen(number: int) -> bool:
    n = number
    total = 0
    while n > 0:
        digit = n % 10
        total += cache[digit]
        if total > number:
            return False
        n = n // 10

    return total == number

@njit(parallel=True)
def main() -> None:
    for n in prange(0, N):
        if is_munchausen(n):
            print(n)

##############################################################################

if __name__ == "__main__":
    main()
jabbalaci commented 8 months ago

Parallel solutions are treated differently. I can add numba but let's start with a single-threaded version. Is it enough to remove this line: @njit(parallel=True) ?

You can also send a PR. It can go in a folder called python3_with_numba.

jabbalaci commented 8 months ago

Thanks, it was added.