← run

bcb-0002

1.000
5/5 tests· lib-knowledge
Challenge · difficulty 2/5
# BigCodeBench/2

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

Allowed libraries: `statistics`, `random`.

```python
import random
import statistics

def task_func(LETTERS):
    """
    Create a dictionary in which keys are random letters and values are lists of random integers.
    The dictionary is then sorted by the mean of the values in descending order, demonstrating the use of the statistics library.
    
    Parameters:
        LETTERS (list of str): A list of characters used as keys for the dictionary.
    
    Returns:
    dict: The sorted dictionary with letters as keys and lists of integers as values, sorted by their mean values.
    
    Requirements:
    - random
    - statistics
    
    Example:
    >>> import random
    >>> random.seed(42)
    >>> sorted_dict = task_func(['a', 'b', 'c'])
    >>> list(sorted_dict.keys())
    ['a', 'b', 'c']
    >>> isinstance(sorted_dict['a'], list)
    True
    >>> type(sorted_dict['a'])  # Check type of values
    <class 'list'>
    """
```

<!-- imported from BigCodeBench (BigCodeBench/2) -->
tests/test_bcb_0002.py
# Auto-generated from BigCodeBench BigCodeBench/2. Do not edit by hand.
import pathlib as _pathlib
exec(_pathlib.Path(__file__).with_name("solution.py").read_text(), globals())

import unittest
class TestCases(unittest.TestCase):
    
    def setUp(self):
        # Setting up a common letters array and sorted dictionary for use in all tests
        self.letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
        self.sorted_dict = task_func(self.letters)
    def test_case_1(self):
        # Check if the function returns a dictionary
        self.assertIsInstance(self.sorted_dict, dict, "The function should return a dictionary.")
    def test_case_2(self):
        # Ensure all keys in the sorted dictionary are within the provided letters
        all_letters = all([key in self.letters for key in self.sorted_dict.keys()])
        self.assertTrue(all_letters, "All keys of the dictionary should be letters.")
        
    def test_case_3(self):
        # Ensure all values are lists of integers
        all_lists = all([isinstance(val, list) and all(isinstance(i, int) for i in val) for val in self.sorted_dict.values()])
        self.assertTrue(all_lists, "All values of the dictionary should be lists of integers.")
        
    def test_case_4(self):
        # Check if the dictionary is sorted by the mean values in descending order
        means = [statistics.mean(val) for val in self.sorted_dict.values()]
        self.assertTrue(all(means[i] >= means[i + 1] for i in range(len(means) - 1)), "The dictionary should be sorted in descending order based on the mean of its values.")
    
    def test_case_5(self):
        # Check if the dictionary includes all provided letters as keys
        self.assertEqual(set(self.sorted_dict.keys()), set(self.letters), "The dictionary should have all provided letters as keys.")
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
import random
import statistics

def task_func(LETTERS):
    """
    Create a dictionary in which keys are random letters and values are lists of random integers.
    The dictionary is then sorted by the mean of the values in descending order, demonstrating the use of the statistics library.
    
    Parameters:
        LETTERS (list of str): A list of characters used as keys for the dictionary.
    
    Returns:
    dict: The sorted dictionary with letters as keys and lists of integers as values, sorted by their mean values.
    
    Requirements:
    - random
    - statistics
    """
    # Create dictionary with letters as keys and lists of random integers as values
    result = {}
    
    for letter in LETTERS:
        # Generate a list of random integers for each letter
        value_list = [random.randint(0, 100) for _ in range(random.randint(1, 10))]
        result[letter] = value_list
    
    # Sort by mean of values in descending order using statistics library
    sorted_items = sorted(result.items(), key=lambda x: statistics.mean(x[1]), reverse=True)
    
    # Create sorted dictionary
    sorted_dict = dict(sorted_items)
    
    return sorted_dict
```

Test output (stdout)

.....                                                                    [100%]
5 passed in 0.03s
Reasoning (chain-of-thought)
Let me analyze this task:

1. I need to create a dictionary where:
   - Keys are random letters from the input LETTERS list
   - Values are lists of random integers

2. The dictionary should be sorted by the mean of the values in descending order

3. I need to use the `statistics` library (specifically `statistics.mean`)

4. I need to use the `random` library for generating random values

Let me think about the implementation:

1. First, I need to generate random letters as keys. Looking at the example, it seems like the keys should be from the LETTERS list, but the example shows `['a', 'b', 'c']` as the output keys. Let me re-read...

Actually, looking at the example more carefully:
- Input: `['a', 'b', 'c']`
- Output keys: `['a', 'b', 'c']`

So it seems like we should use the letters from the LETTERS list as keys. But the docstring says "keys are random letters" - this might mean we randomly select from the LETTERS list, or it might mean we use all letters from LETTERS.

Looking at the example, it appears we should use all letters from the LETTERS list as keys.

2. For each key, we need to generate a list of random integers as values.

3. Then we need to sort the dictionary by the mean of the values in descending order.

Wait, dictionaries in Python 3.7+ maintain insertion order, but we need to sort them. The challenge is that dictionaries don't have a built-in sort method that sorts by values. We need to:
- Create a list of tuples (key, value_list)
- Calculate the mean for each value_list
- Sort by mean in descending order
- Create a new dictionary from the sorted list

Let me write the code:

```python
import random
import statistics

def task_func(LETTERS):
    # Create dictionary with random letters as keys and lists of random integers as values
    result = {}
    
    for letter in LETTERS:
        # Generate a list of random integers for each letter
        value_list = [random.randint(0, 100) for _ in range(random.randint(1, 10))]
        result[letter] = value_list
    
    # Sort by mean of values in descending order
    sorted_items = sorted(result.items(), key=lambda x: statistics.mean(x[1]), reverse=True)
    
    # Create sorted dictionary
    sorted_dict = dict(sorted_items)
    
    return sorted_dict
```

I'll generate random integer lists for each letter, then sort the dictionary by the mean of those lists in descending order. The key steps involve creating random value lists, calculating their means, and sorting the dictionary accordingly.

The implementation ensures we use both `random` and `statistics` libraries as required, with a focus on creating a sorted dictionary based on the mean values.