Initial commit

This commit is contained in:
2024-01-23 14:32:21 +01:00
commit 2898a6bd38
12 changed files with 493 additions and 0 deletions

Binary file not shown.

Binary file not shown.

41
prime_streaming/helper.py Normal file
View File

@ -0,0 +1,41 @@
from threading import Thread
import functools
def timeout(timeout):
def deco(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
res = [Exception('function [%s] timeout [%s seconds] exceeded!' % (func.__name__, timeout))]
def newFunc():
try:
res[0] = func(*args, **kwargs)
except Exception as e:
res[0] = e
t = Thread(target=newFunc)
t.daemon = True
try:
t.start()
t.join(timeout)
except Exception as je:
print ('error starting thread')
raise je
ret = res[0]
if isinstance(ret, BaseException):
raise ret
return ret
return wrapper
return deco
if __name__ == "__main__":
@timeout(timeout=5)
def long_running_function():
import time
time.sleep(10)
return "Function completed successfully"
try:
result = long_running_function()
print(result)
except TimeoutError as e:
print(e)

View File

@ -0,0 +1,5 @@
home = C:\Python312
include-system-site-packages = false
version = 3.12.0
executable = C:\Python312\python.exe
command = C:\Python312\python.exe -m venv C:\Users\GASSERTH\source\bidouilles\codewars\prime_streaming

58
prime_streaming/stream.py Normal file
View File

@ -0,0 +1,58 @@
import numpy as np
def sieve_np(limit):
if limit < 2:
return []
# Create a boolean array "is_prime" and initialize all entries as True
is_prime = np.ones(limit + 1, dtype=bool)
is_prime[0:2] = False # 0 and 1 are not prime numbers
for p in range(2, int(limit**0.5) + 1):
if is_prime[p]:
# Use array slicing to mark all multiples of p as not prime
is_prime[p**2 : limit + 1 : p] = False
# Create a list of prime numbers using NumPy's where function
primes = np.where(is_prime)[0]
return primes.tolist()
def sieve(max_n):
s = [True] * (max_n + 1)
p = 2
while p**2 <= max_n:
if s[p]:
for i in range(p**2, max_n + 1, p):
s[i] = False
p += 1
primes = [p for p in range(2, max_n + 1) if s[p]]
return primes
def sieve_of_eratosthenes(limit):
if limit < 2:
return []
# Create a boolean array "prime[0..limit]" and initialize all entries as True
prime = [True] * (limit + 1)
prime[0] = prime[1] = False # 0 and 1 are not prime numbers
p = 2
while p**2 <= limit:
if prime[p]:
# Update all multiples of p starting from p^2
prime[p**2 : limit + 1 : p] = [False] * len(prime[p**2 : limit + 1 : p])
p += 1
# Create a list of prime numbers
primes = [p for p in range(2, limit + 1) if prime[p]]
return primes
class Primes:
primes = sieve(25_000_000)
@staticmethod
def stream():
yield from Primes.primes