import random


def generate_name(start, markov_chain, max_words=2):
    """Generate a new town name, given a start syllable and a Markov chain.

    This function takes a single start syllable or a list of start syllables,
    one of which is then chosen randomly, and a corresponding Markov chain to
    generate a new fictional town name. The number of words in the name can
    optionally be passed in as an argument and defaults to 2 otherwise.

    Note that it is possible that the generated name already exists. To avoid
    that, one should check whether the name exists against the set of input
    names.
    """
    while True:
        if isinstance(start, list):
            # If start is a list choose a syllable randomly
            next_syllable = random.choice(start)
        else:
            next_syllable = start

        # Initialise new name
        new_name = next_syllable

        while True:
            # Choose next syllable from the Markov chain
            next_syllable = random.choice(markov_chain[next_syllable])

            # Return if end of word has been reached
            if next_syllable == 0:
                break
            else:
                new_name += next_syllable

        # Remove leading and trailing spaces
        new_name = new_name.strip()

        # Make sure name has less words than max_words, otherwise start over
        if len(new_name.split(" ")) <= max_words:
            break

    # Capitalise every word in the new name
    new_name = " ".join([word.capitalize() for word in new_name.split(" ")])
    return new_name