Skip to content

Instantly share code, notes, and snippets.

@neosergio
Last active August 19, 2021 17:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neosergio/eb8b3dd3971c8d63dbed6b59fd2ab29f to your computer and use it in GitHub Desktop.
Save neosergio/eb8b3dd3971c8d63dbed6b59fd2ab29f to your computer and use it in GitHub Desktop.

Parse a list of Names

For the following list of names:

NAMES = ['arnold schwarzenegger', 'alec baldwin', 'bob belderbos',
         'julian sequeira', 'sandra bullock', 'keanu reeves',
         'julbob pybites', 'bob belderbos', 'julian sequeira',
         'al pacino', 'brad pitt', 'matt damon', 'Brad pitt']
  • First you will write a function to take out duplicates and title case them.
  • Then you will sort the list in alphabetical descending order by surname and lastly determine what the shortest first name is. For this exercise you can assume there is always one name and one surname.

Proposed solution

def dedup_and_title_case_names(names):
    """Should return a list of title cased names,
       each name appears only once"""
    names = [name.title() for name in names]
    names = list(dict.fromkeys(names))
    return names
    


def sort_by_surname_desc(names):
    """Returns names list sorted desc by surname"""
    names = dedup_and_title_case_names(names)
    names = [name.split() for name in names]
    names = sorted(names, reverse=True, key = lambda x: x[1])
    names = [' '.join(name) for name in names]
    return names
    # ...


def shortest_first_name(names):
    """Returns the shortest first name (str).
       You can assume there is only one shortest name.
    """
    names = dedup_and_title_case_names(names)
    names = [name.split() for name in names]
    names = sorted(names, key = lambda x: len(x[0]))
    shortest = names[0][0]
    return str(shortest)

Unit testing

Write tests at least to check each function return

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment