Question 30
Given the following code:
Which of the following statements is true about the list l returned by foo(x, ds)?
len(l) == len(set(l))len(l) > 0 == Trueonly ifx in ds == Truelis an empty list ifds.get(x)returnsNonelis equivalent to[ds[x]]- All of the above
Solution
Assume x is either an int, float, string (some primitive value), and ds is a dictionary.
For simplicity, let's assume ds = {'a': 1, 'b': 2, 'c': 3, 'd': 1, 3: 'c'} and consequently x is either an integer or string value.
- The if statement in the for loop assumes that if a value
vstored in dictionarydsis equal tox, then we add its keykintol. lwill very likely contain keys of dictionaryds. For example,foo(2, ds)will return['b']. This would not be the same asds[x], as you're treating a compared valuevas a key. Hence, OPTION 4:lis equivalent to[ds[x]]is incorrect. Consequently, OPTION 5: "All of the above" is also incorrect.x in dsis effectively the same as checking if any valuevis a key inds- while this holds ifx = 'c'orx = 3, this will not work for the other key-value pairs inds. Hence, OPTION 2:len(l) > 0 == Trueonly ifx in ds == Trueis incorrect.foo()adds keyskintolif the corresponding valuevis equals tox, the latter of which is not the same asds.get(x), which tries to check if a valuevis a key inds, return the corresponding valueds[x]if any andNoneotherwise. Hence, this is not indicative of how many elementslwill have. Therefore, OPTION 3:lis an empty list ifds.get(x)returnsNoneis incorrect.- Dictionaries work such that every key value is distinct.
Given this logic, since
lwill very likely contain keys of dictionaryds, the length oflwould be the same even if converted into a set. Hence, OPTION 1:len(l) == len(set(l))is correct.
NOTE: This is a tough one, I understand if you can't wrap your head around this one. 😅
Answer
len(l) == len(set(l))