RAREST Method Write a method rarest that accepts a map whose

RAREST Method

Write a method rarest that accepts a map whose keys are strings and whose values are integers as a parameter and returns the integer value that occurs the fewest times in the map. If there is a tie, return the smaller integer value. If the map is empty, throw an exception.

For example, suppose the map contains mappings from students\' names (strings) to their ages (integers). Your method would return the least frequently occurring age. Consider a map variable m containing the following key/value pairs:

Three people are age 20 (Jeff, Kasey, and Kim), two people are age 22 (Alyssa and Stef), and four people are age 25 (Char, Dan, Mogran, and Ryan). So a call of rarest(m) returns 22 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 Kelly=22 to the map above, there would now be a tie of three people of age 20 (Jeff, Kasey, Kim) and three people of age 22 (Alyssa, Kelly, Stef). So a call of rarest(m) would now return 20 because 20 is the smaller of the rarest values.

Solution

Rarest Method:

Algorithm:

Input: Key value pairs as a dictionary

Expected output: Least frequent value from key value pairs

We see that \'22\' has occurred twice, and \'25\' four times. Now we have to find it using out algorithm:

Now, we have the following values in \'min_age\' and \'frequency\' variables:
min_age = 22
frequency = 2

If we add kelly to the initial key value pair, we will get the min_age as 20 and frequency as 3 as expected.

The following python code can be referred to understand the algorithm:
  
   def rarest(d):
age_count = {}
  
for key,value in d.items():
if value in age_count:
age_count[value]+=1
else:
age_count[value]=1
  
min_age=0
freq=0
  
for key,value in age_count.items():
if freq==0:
freq=value
min_age=key
elif freq>value:
freq=value
min_age=key
elif freq==value:
if min_age>key:
min_age=key
  
return min_age,freq,frd
  
d={\'Alyssa\':22, \'Char\':25, \'Dan\':25, \'Jeff\':20, \'Kasey\':20, \'Kim\':20, \'Mogran\':25, \'Ryan\':25, \'Stef\':22}

r = rarest(d)

print(r)

RAREST Method Write a method rarest that accepts a map whose keys are strings and whose values are integers as a parameter and returns the integer value that oc
RAREST Method Write a method rarest that accepts a map whose keys are strings and whose values are integers as a parameter and returns the integer value that oc

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site