logo CodeStepByStep logo

last_names_by_age

Language/Type: Python dict collections

Write a function named last_names_by_age that accepts three parameters: 1) a dictionary where each key is a person's full name (a string) and the associated value is that person's age (an integer) 2) an integer for a minimum age and 3) an integer for a max age. Your function should return a new dictionary with information about people with ages between the min and max, inclusive. You should process the keys of the dictionary in sorted order.

In your result dictionary, each key is an integer age, and the value for that key is a string with the last names of all people at that age, separated by "and" if there is more than one person of that age. The order of names for a given age should be in the order they occurred in the parameter dictionary. Include only ages between the min and max inclusive, where there is at least one person of that age in the parameter dictionary. If the dictionary passed is empty, or if there are no people in the dictionary between the min/max ages, return an empty dictionary.

Some names are in the format 'first last' such as 'Marty Stepp'. But a name could have more tokens, such as 'Oscar de la Hoya', or could contain just a single token, such as 'Cher'. For example, if a dictionary named ages stores the following key/value pairs:

{'Allison L. Smith': 18, 'Benson Kai Lim': 48, 'David L Shaw': 20, 'Erik Thomas Jones': 20,
 'Galen Wood': 15, 'Madonna': 25, 'Helene Q. Martin': 40, 'Janette Siu': 18,
 'Jessica K. Miller': 35, 'Marty Douglas Stepp': 35, 'Paul Beame': 28, 'Sara de la Pizza': 15,
 'Stuart T. Reges': 98, 'Tyler Rigs': 6, 'Prince': 20
 

The call of last_names_by_age(ages, 16, 25) should return the following dictionary:

{18: 'Smith and Siu', 20: 'Shaw and Jones and Prince', 25: 'Madonna'

For the same dictionary, the call of last_names_by_age(ages, 20, 40) should return the following dictionary:

{20: 'Shaw and Jones and Prince', 25: 'Young', 28: 'Beame', 35: 'Miller and Stepp', 40: 'Martin'

Constraints: Obey the following restrictions in your solution.

  • You will need to construct a dictionary to store your results, but you may not use any other structures (lists, lists, etc.) as auxiliary storage. (You can have as many simple variables as you like.)
  • You should not modify the contents of the dictionary passed to your function.
    Declare your function in such a way that any caller can be sure that this will not happen.
  • Your solution should run in no worse than O(N log N) time, where N is the number of pairs in the dictionary.
Function: Write a Python function as described, not a complete program.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.