파이썬 소수 필터 함수
Wikiprompt, 무료 프롬프트 백과사전에서
파이썬 소수 필터 함수 정렬되지 않은 정수 리스트에서 소수를 필터링하는 최적화된 Python 함수를 요청하는 프롬프트.
프롬프트 내용저장
🌐
Here is a Python function that extracts prime numbers from an unsorted list, optimized for performance without external libraries:
```python
def get_primes(numbers):
"""
Returns a new list containing only the prime numbers from the input list.
Optimized for performance using a sieve approach for the maximum value.
"""
if not numbers:
return []
# Find the maximum value in the list to bound the sieve
max_val = max(numbers)
if max_val < 2:
return []
# Sieve of Eratosthenes to mark primes up to max_val
sieve = [True] * (max_val + 1)
sieve[0] = sieve[1] = False
for i in range(2, int(max_val ** 0.5) + 1):
if sieve[i]:
for j in range(i * i, max_val + 1, i):
sieve[j] = False
# Filter the original list, preserving order and duplicates
return [num for num in numbers if num >= 2 and sieve[num]]
```
**Explanation of optimizations:**
1. **Sieve of Eratosthenes**: Instead of testing each number individually (which would be O(n * sqrt(m))), we precompute all primes up to the maximum value in the list. This reduces the complexity to O(m log log m) for the sieve plus O(n) for filtering, where m is the max value and n is the list length.
2. **Early exit**: If the list is empty or the maximum value is less than 2, we return an empty list immediately.
3. **Memory efficiency**: The sieve uses a boolean list of size max_val + 1, which is efficient for typical integer ranges.
4. **Preserves order and duplicates**: The final list comprehension iterates through the original list, so the output maintains the original order and includes duplicate primes if they appear.
**Example usage:**
```python
print(get_primes([10, 7, 3, 5, 2, 11, 4, 7])) # Output: [7, 3, 5, 2, 11, 7]
print(get_primes([1, 4, 6, 8, 9])) # Output: []
print(get_primes([-5, 0, 2, 3, 5])) # Output: [2, 3, 5]
```
**Performance note**: For very large lists with a high maximum value, this approach is significantly faster than trial division. However, if the list contains extremely large numbers (e.g., > 10^7), the sieve may consume too much memory. In such cases, a hybrid approach using trial division with precomputed small primes could be considered, but for most practical scenarios, this sieve-based method is optimal.
전체 프롬프트를 보려면 로그인하세요
Continue with:
By logging in, you agree to our Terms of Use and Privacy Policy
사용법
이 프롬프트는 coding와 함께 사용하도록 설계되었습니다. 위의 프롬프트 내용을 복사하여 원하는 AI 도구에 붙여넣으세요.
최상의 결과를 얻으려면 자리 표시자(대괄호 또는 대문자로 표시)를 특정 요구 사항으로 사용자 지정할 수 있습니다.
토론
댓글 0개