logo CodeStepByStep logo

rarest_age

Language/Type: Python dict collections

Write a function named rarest_age that accepts as a parameter a dictionary from students' names (strings) to their ages (integers), and returns the least frequently occurring age. Consider a dictionary variable named m containing the following key/value pairs:

{'Char': 45, 'Dan': 45, 'Jerry': 23, 'Kasey': 10, 'Jeff': 10, 'Elmer': 45, 'Kim': 10, 'Ryan': 45, 'Mehran': 23}

Three people are age 10 (Kasey, Jeff, and Kim), two people are age 23 (Jerry and Mehran), and four people are age 45 (Char, Dan, Elmer, and Ryan). So a call of rarest_age(m) returns 23 because only two people are that age.

If there is a tie (two or more rarest ages that occur the same number of times), return the youngest age among them. For example, if we added another pair of 'Steve': 23 to the dictionary above, there would now be a tie of three people of age 10 (Kasey, Jeff, Kim) and three people of age 23 (Jerry, Mehran, Steve). So a call of rarest_age(m) would now return 10 because 10 is the smaller of the rarest values. This implies that if every person in the dictionary has a unique age, your function would return the smallest of all the ages in the dictionary.

If the dictionary passed to your function is None or empty, your function should return 0. You may assume that no key or value stored in the dictionary is None. Otherwise you should not make any assumptions about the number of key/value pairs in the dictionary or the range of possible ages that could be in the dictionary.

Constraints: You may create one collection of your choice as auxiliary storage to solve this problem. You can have as many simple variables as you like. You should not modify the contents of the dictionary passed to your function.

Type your Python solution code here:

This is a function exercise. Write a Python function as described. Do not write a complete program; just the function(s) above.

You must log in before you can solve this problem.

Log In

Need help?

If you do not understand how to solve an exercise or why your solution doesn't work, please contact your TA or instructor.
If something seems wrong with the site (errors, slow performance, incorrect tests, etc.), please

Is there a problem? Contact a site administrator.

©, all rights reserved.