In: Computer Science
\
Implement function find_key that takes a
dictionary with int:int pairs and a second parameter which is an
int that corresponds to one of the dictionary values, and returns
the key that corresponds to this value. If there are more than one
keys, it returns the smallest key. If there is no key that maps to
this value, the functions returns False. You may not use the
.values and .items methods. You may not create lists, tuples,
strings, sets, dictionaries. You maynot use functions min, max,
sorted.
Examples:
find_key({5:7, 6:3, 2:1, 3:4}, 4) -> 3
find_key({1:9, 7:4, 6:3, 2:1, 8:4}, 4) -> 7
find_key({9:5, 6:3, 2:1, 3:3}, 4) -> False
True
False
In python Please
def find_key(a,b):
c=0
m=0
for i in a:
if a[i]==b:
m=i
break
for i in a:
if a[i]==b:
if i<m:
m=i
else:
c+=1
if c==len(a):
return False
else:
return m
if __name__=='__main__':
print(find_key({5:7, 6:3, 2:1, 3:4}, 4))
print(find_key({1:9, 7:4, 6:3, 2:1, 8:4}, 4))
print(find_key({9:5, 6:3, 2:1, 3:3}, 4))
Explanation -
def find_key(a,b):
c=0
m=0
Define a function named find_key which accepts 2 parameters a which is a dictionary and b is an integer which corresponds to one of the dictionary values.
Also define variables m and c , both initialized to 0 which will be used later in the program.
for i in a:
if a[i]==b:
m=i
break
Using for loop iterate through every key in a and check if value of that corresponding key is equal to b . if yes then
m=i and exit the loop.It means we have found our first matched key
for i in a:
if a[i]==b:
if i<m:
m=i
else:
c+=1
Again using for loop iterate through every key in a and check if value of that corresponding key is equal to b . if yes then check if its less than m which was computed in the above step i.e m = first found matched key(i)
if it is less than store this key in m variable else keep m as it is,
Also , while iterating through every key in a , if value of that corresponding key is NOT equal to b .Increment c by 1.
if c==len(a):
return False
else:
return m
Now check if c is equal to length of dictionary a . if it is equal it means none of the key value matched with b.
if c is not equal to length of dictionary a then the function will return m which is nothing but the key of the dictionary whose value matched with b and is smallest among all keys whose value matched with b.
if __name__=='__main__':
print(find_key({5:7, 6:3, 2:1, 3:4}, 4))
print(find_key({1:9, 7:4, 6:3, 2:1, 8:4}, 4))
print(find_key({9:5, 6:3, 2:1, 3:3}, 4))
Finally in main , call the function by passing the arguments as shown above.