In: Computer Science
Use Python for this quetions:
Write a python functions that use Dictionary to:
1) function name it addToDictionary(s,r)
that take a string and add it to a dictionary if the string exist increment its frequenc
2) function named freq(s,r)
that take a string and a record if the string not exist in the dictinary it return 0 if it exist it should return its frequancy.
Explanation:-
Dictionary in python works like map where we have two things key:value pair where we can find value corresponding to each key .In addToDictionary() funciton what we did is we checked if that key is present in the dictionary or not if it is present then we just incremented its value and if it is not present then we pushed the new string into the dictionary . In freq() we just returned the value corresponding to that key in the record and if it is not present we just returned 0.
CODE:-
record = {"a":1,"b":2,"c":3}
def addToDictionary(s,r):
if r.get(s) == None:
r[s]=1
else:
r[s]=r[s]+1
def freq(s,r):
if r.get(s)==None:
return 0
return r[s]
print("-----record before any operation---")
print(record)
addToDictionary("d",record)
print("-------a key is added--------")
print(record)
print("-----use freq function to find freq of alphabet
\"a\"-------")
print(freq("a",record))
OUTPUT:-