Python Write a function least_common that accepts a dictionary whose keys are st
ID: 3716566 • Letter: P
Question
Python Write a function least_common that accepts a dictionary whose keys are strings and whose values are integers as a parameter and returns the integer value that occurs the fewest times in the dictionary. For example, if a dictionary named m contains {'Alyssa': 22, 'Char': 25, 'Dan': 25, 'Jeff': 20, 'Kasey': 20, 'Kim': 20, 'Mogran': 25, 'Ryan': 25', 'Stef': 22}, the call of least_common(m) returns 22. If there is a tie, return the smaller integer value. If the map is empty, throw a ValueError.
Explanation / Answer
def least_common(m):
n=-1#to store the least frequent item value
c=0#to count the present letter frequency
cp=-1#to store the previous letter frequency
for v in m:#for all keys in m
val=m[v]#taking value
c=0
for k in m:
val2=m[k]
if(val==val2):
c+=1
if(cp==-1):#updating least frequent item
cp=c
n=val
elif (cp>c):
cp=c
n=val
return n
m= {'Alyssa': 22, 'Char': 25, 'Dan': 25, 'Jeff': 20, 'Kasey': 20, 'Kim': 20, 'Mogran': 25, 'Ryan': 25, 'Stef': 22}
print(least_common(m))
n = {}
print(least_common(n))
output:
>>> ================================ RESTART ================================
>>>
22
-1
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.