← run

bcb-0001

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

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

Allowed libraries: `collections`, `random`, `string`.

```python
import collections
import random
import string

def task_func(length=100):
    """
    Generate a random string of the specified length composed of uppercase and lowercase letters, 
    and then count the occurrence of each character in this string.

    Parameters:
    length (int, optional): The number of characters in the generated string. Default is 100.

    Returns:
    dict: A dictionary where each key is a character from the generated string and the value 
            is the count of how many times that character appears in the string.

    Requirements:
    - collections
    - random
    - string

    Raises:
    ValueError if the length is a negative number

    Example:
    >>> import random
    >>> random.seed(42)  # Ensures reproducibility for demonstration
    >>> task_func(10)
    {'h': 1, 'B': 2, 'O': 1, 'L': 1, 'm': 1, 'j': 1, 'u': 1, 'E': 1, 'V': 1}
    """
```

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

import unittest
import string
class TestCases(unittest.TestCase):
    def setUp(self):
        # Prepare valid characters and set a random seed for reproducibility
        self.valid_chars = string.ascii_uppercase + string.ascii_lowercase
        random.seed(42)  # Ensuring reproducibility for tests
    def test_generated_string_properties(self):
        # Consolidated test for different lengths to check structure and correctness
        test_lengths = [10, 50, 100, 150, 5]
        for length in test_lengths:
            with self.subTest(length=length):
                result = task_func(length)
                self.assertTrue(len(result) <= length, "Length of result should be <= requested string length")
                self.assertEqual(sum(result.values()), length, f"Total counts should sum to {length}")
                self.assertTrue(all(char in self.valid_chars for char in result), "All characters should be valid letters")
    def test_zero_length(self):
        # Test edge case where length is zero
        result = task_func(0)
        self.assertEqual(len(result), 0, "Result should be empty for zero length")
        self.assertEqual(sum(result.values()), 0, "Sum of counts should be zero for zero length")
    def test_negative_length(self):
        # Test handling of negative length input
        with self.assertRaises(ValueError, msg="Negative length should raise an error"):
            task_func(-1)
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 collections
import random
import string

def task_func(length=100):
    """
    Generate a random string of the specified length composed of uppercase and lowercase letters, 
    and then count the occurrence of each character in this string.

    Parameters:
    length (int, optional): The number of characters in the generated string. Default is 100.

    Returns:
    dict: A dictionary where each key is a character from the generated string and the value 
            is the count of how many times that character appears in the string.

    Requirements:
    - collections
    - random
    - string

    Raises:
    ValueError if the length is a negative number

    Example:
    >>> import random
    >>> random.seed(42)  # Ensures reproducibility for demonstration
    >>> task_func(10)
    {'h': 1, 'B': 2, 'O': 1, 'L': 1, 'm': 1, 'j': 1, 'u': 1, 'E': 1, 'V': 1}
    """
    if length < 0:
        raise ValueError("Length cannot be negative")
    
    # Generate a random string of uppercase and lowercase letters
    characters = string.ascii_letters
    random_string = ''.join(random.choices(characters, k=length))
    
    # Count the occurrence of each character
    char_counts = collections.Counter(random_string)
    
    return dict(char_counts)
```

Test output (stdout)

...                                                                      [100%]
3 passed in 0.02s