from typing import Sequence
import random


def gen_rhythm(
    beats: int = 4, note_values: Sequence[int] = (8, 6, 4, 3, 2, 1)
) -> Sequence[int]:
    """Generates a rhythm of the given length with the given note values.

    Args:
      beats: Length of the rhythm to generate in quarter notes (default 4)
      note_values: The note values in 8th notes to use when generating the
        rhythm. For instance, a quarter note's note value would be 2 (two
        8th notes). (default (8, 6, 4, 3, 2, 1))

    Returns:
      A sequence of notes by their values in 8ths. For example, [1, 3] would
      be an 8th note followed by a dotted quarter note.

    Raises:
      ValueError: It may not be possible to generate a rhythm of a given
        length given specific note values. If that happens, this error
        is raised.
    """

    iter_max = 500

    notes = [0]
    eighths = beats * 2
    current_eighths = 0
    iter_counter = 0
    while current_eighths != eighths:
        iter_counter += 1
        if iter_counter > iter_max:
            raise ValueError(
                "Given note values cannot create rhythm of the given length"
            )

        current_eighths -= notes.pop()

        while current_eighths < eighths:
            note_val = random.choice(note_values)
            notes.append(note_val)
            current_eighths += note_val

    return notes