Generate and Count Zebra Stripes

  • Share this:

Code introduction


This function takes two arguments: a list of colors and an integer representing the number of stripes. It generates a random list of stripes and counts the number of each color stripe.


Technology Stack : collections.Counter, typing.List, random.choice

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zebra(arg1, arg2):
    from collections import Counter
    from typing import List
    import random

    def generate_zebra_stripes(colors: List[str], num_stripes: int) -> List[str]:
        if num_stripes <= 0:
            return []
        stripes = [random.choice(colors) for _ in range(num_stripes)]
        return stripes

    def count_stripes(stripes: List[str]) -> dict:
        counter = Counter(stripes)
        return dict(counter)

    if not isinstance(arg1, list) or not isinstance(arg2, int):
        raise TypeError("arg1 must be a list of colors and arg2 must be an integer representing the number of stripes.")

    return generate_zebra_stripes(arg1, arg2), count_stripes(generate_zebra_stripes(arg1, arg2))