← run

he-000

1.000
1/1 tests· basic
Challenge · difficulty 2/5
# HumanEval/0

Implement a file **`solution.py`** that completes the function below. Keep the given name and signature; your file must define it at module level.

```python
from typing import List


def has_close_elements(numbers: List[float], threshold: float) -> bool:
    """ Check if in given list of numbers, are any two numbers closer to each other than
    given threshold.
    >>> has_close_elements([1.0, 2.0, 3.0], 0.5)
    False
    >>> has_close_elements([1.0, 2.8, 3.0, 4.0, 5.0, 2.0], 0.3)
    True
    """
```

<!-- imported from OpenAI HumanEval (HumanEval/0) -->
tests/test_he_000.py
# Auto-generated from OpenAI HumanEval HumanEval/0. Do not edit by hand.
from solution import *  # noqa: F401,F403 (prompt helpers may be referenced by tests)
from solution import has_close_elements as candidate

METADATA = {
    'author': 'jt',
    'dataset': 'test'
}


def check(candidate):
    assert candidate([1.0, 2.0, 3.9, 4.0, 5.0, 2.2], 0.3) == True
    assert candidate([1.0, 2.0, 3.9, 4.0, 5.0, 2.2], 0.05) == False
    assert candidate([1.0, 2.0, 5.9, 4.0, 5.0], 0.95) == True
    assert candidate([1.0, 2.0, 5.9, 4.0, 5.0], 0.8) == False
    assert candidate([1.0, 2.0, 3.0, 4.0, 5.0, 2.0], 0.1) == True
    assert candidate([1.1, 2.2, 3.1, 4.1, 5.1], 1.0) == True
    assert candidate([1.1, 2.2, 3.1, 4.1, 5.1], 0.5) == False


def test_he_000():
    check(candidate)
System prompt
You are an expert programmer. Solve the task exactly as specified. Output your solution as fenced code blocks using the required file name(s) and the exact function/type signatures requested. Prefer correctness; do not include prose outside code unless asked.
Proposed solution
```python
from typing import List


def has_close_elements(numbers: List[float], threshold: float) -> bool:
    """ Check if in given list of numbers, are any two numbers closer to each other than
    given threshold.
    >>> has_close_elements([1.0, 2.0, 3.0], 0.5)
    False
    >>> has_close_elements([1.0, 2.8, 3.0, 4.0, 5.0, 2.0], 0.3)
    True
    """
    # If there are fewer than 2 elements, no pair exists
    if len(numbers) < 2:
        return False
    
    # Sort the numbers to efficiently check adjacent elements
    sorted_numbers = sorted(numbers)
    
    # Check adjacent pairs only - if any pair has difference < threshold, return True
    for i in range(len(sorted_numbers) - 1):
        if abs(sorted_numbers[i+1] - sorted_numbers[i]) < threshold:
            return True
    
    return False
```

Test output (stdout)

.                                                                        [100%]
1 passed in 0.01s