← run

he-020

1.000
1/1 tests· algorithms
Challenge · difficulty 3/5
# HumanEval/20

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, Tuple


def find_closest_elements(numbers: List[float]) -> Tuple[float, float]:
    """ From a supplied list of numbers (of length at least two) select and return two that are the closest to each
    other and return them in order (smaller number, larger number).
    >>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.2])
    (2.0, 2.2)
    >>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.0])
    (2.0, 2.0)
    """
```

<!-- imported from OpenAI HumanEval (HumanEval/20) -->
tests/test_he_020.py
# Auto-generated from OpenAI HumanEval HumanEval/20. Do not edit by hand.
from solution import *  # noqa: F401,F403 (prompt helpers may be referenced by tests)
from solution import find_closest_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]) == (3.9, 4.0)
    assert candidate([1.0, 2.0, 5.9, 4.0, 5.0]) == (5.0, 5.9)
    assert candidate([1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2)
    assert candidate([1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.0)
    assert candidate([1.1, 2.2, 3.1, 4.1, 5.1]) == (2.2, 3.1)


def test_he_020():
    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, Tuple


def find_closest_elements(numbers: List[float]) -> Tuple[float, float]:
    """ From a supplied list of numbers (of length at least two) select and return two that are the closest to each
    other and return them in order (smaller number, larger number).
    >>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.2])
    (2.0, 2.2)
    >>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.0])
    (2.0, 2.0)
    """
    if len(numbers) < 2:
        raise ValueError("List must contain at least two elements")
    
    # Sort the numbers to make finding closest pairs efficient
    sorted_numbers = sorted(numbers)
    
    # Initialize with the first pair
    min_diff = abs(sorted_numbers[1] - sorted_numbers[0])
    closest_pair = (sorted_numbers[0], sorted_numbers[1])
    
    # Check each adjacent pair in the sorted list
    for i in range(1, len(sorted_numbers) - 1):
        diff = abs(sorted_numbers[i + 1] - sorted_numbers[i])
        if diff < min_diff:
            min_diff = diff
            closest_pair = (sorted_numbers[i], sorted_numbers[i + 1])
    
    return closest_pair
```

Test output (stdout)

.                                                                        [100%]
1 passed in 0.01s